在碎片计划任务返回getActivity为空 [英] Scheduled Task in Fragment returns getActivity as null
问题描述
我知道类似类型的问题之前问。不好意思再问。
我有一个标签FragmentActivity片段。内片段onActivityCreated 中,我必须安排任务后每隔固定间隔。
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);
以上code工作完全正常,直到我们在在标签活动preSS后退按钮。
一旦后退按钮pressed它抛出以上code的getActivity()的空指针异常。
我猜可能是片段的活性,因此getActivity()方法返回null已分离。
我的问题是如何实现上述方案,使这一进程应该继续,即使后退按钮是pssed $ P $。任何最佳做法?
我从FragmentPageAdapter在返回方法的getItem片段的同一个实例。
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.
在此先感谢!
推荐答案
FragmentManager
设置片段的 mActivity
字段不久在 onAttach()
键,将其设置为空
后不久 onDetach()
(请参阅<一个href=\"http://grep$c$c.com/file/repository.grep$c$c.com/java/ext/com.google.android/android/4.3_r2.1/android/app/FragmentManager.java/#1021\"相对=nofollow>来源$ C $ C ),所以我的猜测是,你正在尝试执行 getActivity()
要么过于太早或太晚片段生命周期。
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.
这篇关于在碎片计划任务返回getActivity为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!