Scheduled Task in Fragment returns getActivity as null

陌路散爱 提交于 2019-12-12 21:05:59

问题


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:


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.



来源:https://stackoverflow.com/questions/18579603/scheduled-task-in-fragment-returns-getactivity-as-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!