Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Fragment getActivity() = null

I'm using fragments in my application. And the very common problem while using them are the NPE when using getActivity(). I know we can solve it by checking if getActivity() != null every single time or checking if the fragment isAdded().

In one of my classes I'm getting activity's context in more than 60 places. Checking if getActivity()is not null or if the fragment is still added to the activity in all the places is making the code ugly,larger and non-maintainable. Is there any other way to handle this? Is it even possible to destroy the fragment(and stop any work it has been doing while being removed) when it is removed from the activity?

Also Is this way a suggested one?

like image 349
LoveMeSomeFood Avatar asked Jan 14 '14 22:01

LoveMeSomeFood


People also ask

Why does getActivity return null?

If you call it in the constructor of Fragment , it will return null . Just call getActivity() when the method onCreateView() is executed. Save this answer.


2 Answers

In my experience, most cases of getActivity() returning null are in asynchronous callbacks.

For example, your fragment fires an AsyncTask, and then gets removed before the the background job is done, then when the background job finishes and calls getActivity() in onPostExecute(), it will get a null since the fragment is already detached from the activity.

My solution:

1.Check getActivity()==null at the beginning of every asynchronous callback, if it's the case then just abort the method.

2.Cancel asynchronous jobs in onDetach().

And I think this is a better solution than saving the activity instance in onAttach(), because since your fragment is removed, why bother doing all the jobs left in the callbacks(in most cases UI codes)?

like image 111
handhand Avatar answered Sep 24 '22 13:09

handhand


getActivity will be reinitilized in method - onActivityCreated().

So it's safer to call getActivity() right after onActivityCreated() (according to lifecycle of fragments http://developer.android.com/guide/components/fragments.html) - for example in onStart() - in that case it's WILL BE NEVER NULL - no need to do useless checks like isAdded and getActivity != null.

P.S. If we use that solution:

@Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActivity = activity;
    }

mActivity will be never null - but later in method onActivityCreated() getActivity() became different with mActivity. My opinion - sure we can save whole activity in variable, but it's safer to follow android fragments lifecycle workflow and get activity right after onActivityCreated()

like image 4
Alexey O. Avatar answered Sep 22 '22 13:09

Alexey O.