Scheduled Task in Fragment returns getActivity as null

1k views Asked by At

I know similar type of question is asked before. Sorry to ask again.
I have a fragment in a tab FragmentActivity. Within the fragment in onActivityCreated, I have to schedule a task after every fix interval.

Timer t = new Timer();
t.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
   getActivity().runOnUiThread(new Runnable() {
            @Override
    public void run() {
        new fetchDataInBackground(ctx).execute();           //async task
    }
   });
}
}, 0, 20000);

The above code works perfectly fine, until we press the back button over the tab activity.
Once back button is pressed it throws the null pointer exception on getActivity() of above code.
I guess may be fragment have been detached from the activity therefore getActivity() is returning null. My question is how to achieve above scenario, so that the process should continue even if the back button is pressed. Any best practices?
I am returning the same instance of Fragment in getItem method from the FragmentPageAdapter.

Thanks in advance!

1

There are 1 answers

0
Alex Lockwood On

FragmentManager sets the fragment's mActivity field shortly after onAttach() and sets it to null shortly after onDetach() (see the source code), so my guess is that you are trying to execute getActivity() either too early or too late in the fragment lifecycle.