francesco bocci francesco bocci - 1 year ago 90
Android Question

Why View Fragment is null in AsyncTask?

This is my Fragment class:

public class StanzeFragment extends Fragment {

public StanzeFragment(){}

Button vis_stanze;
public TextView testo;

View rootView;

public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

rootView = inflater.inflate(R.layout.activity_log_stanze, container, false);
testo = (TextView) rootView.findViewById(;

vis_stanze = (Button)rootView.findViewById(;
vis_stanze.setOnClickListener( new View.OnClickListener() {

public void onClick(View v) {

getStanze backgroundTask = new getStanze();
return rootView;

public void setTesto(String value){

But now i need to call method "setTesto" in other class (AsyncTask class), in onPostExecute method:

protected void onPostExecute(String result) {
StanzeFragment test = new StanzeFragment();

He give me this error:

" java.lang.NullPointerException: Attempt to invoke virtual method 'void com.androidnuovosa.bocci.navdriwerdb.Utente.StanzeFragment.setTesto(java.lang.String)' on a null object reference" ..
..I think because he don't see View of Fragment, how can I resolve this problem?
Thnks for answer. (I have this problem for other class too)


AsyncTask isn't in StanzeFragment

Answer Source

Fragments are supposed to be instantiated by the system (as they are defined in the layout XML) or from the code by using the FragmentManager methods.

If you just instantiate a StanzeFragment like that, it does not actually appear on the view stack and its testo TextView is null. This seems to be your problem.

In your case apparently the Fragment is already visible when the AsyncTask runs, you should just get a reference to that Fragment instance instead of creating a new one.

The FragmentManager has methods to find a Fragment either by the id (as defined in the XML) or by the tag (given when showing it programmatically):



Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download