francesco bocci francesco bocci - 2 months ago 7
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(R.id.testo);

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

@Override
public void onClick(View v) {

getStanze backgroundTask = new getStanze();
backgroundTask.execute();
}
});
return rootView;
}

public void setTesto(String value){
testo.setText(value);
}
}


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

@Override
protected void onPostExecute(String result) {
StanzeFragment test = new StanzeFragment();
test.setTesto(result);
}


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)

EDIT:

AsyncTask isn't in StanzeFragment

Answer

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):

findFragmentById()

findFragmentByTag()