被替换片段,而AsyncTask的执行 - NullPointerException异常的getActivity() [英] Fragments being replaced while AsyncTask is executed - NullPointerException on getActivity()

查看:253
本文介绍了被替换片段,而AsyncTask的执行 - NullPointerException异常的getActivity()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我将我的活动片段。

I recently converted my Activities to Fragments.

使用类似于制表导航东西,当用户选择另一个标签的片段替换。 之后的片段填充我开始至少一个的AsyncTask来从网上的一些信息。但是 - 如果用户切换到另一个标签,就像正在执行从我的AsyncTask的doBackground法 - 的片段是替换,因此我得到一个 NullPointerException异常在标线:

Using something similar to Tab-Navigation the fragments are replaced when the user selects another tab. After the fragment is populated I start at least one AsyncTask to get some information from the internet. However - if the user switches to another tab just as the doBackground-method from my AsyncTask is being executed - the fragment is replaced and thus I am getting a NullPointerException in the marked lines:

@Override
protected Object doInBackground(Object... params) {
  ...
  String tempjson = helper.SendPost(getResources().getText(R.string.apiid)); //ERROR: Fragment not attached
  ...
}

protected onPostExecute(Object result) {
  ...
  getActivity().getContentResolver() //NULLPOINTEREXCEPTION
  getView().findViewById(R.id.button) //NULL
  ...
}

getActivity() getResources()将导致一个错误,因为我的片段被替换。

getActivity() and getResources() causes an error because my Fragment is replaced.

我尝试过的事情:

  • 在呼唤我的AsyncTask的取消方法(不会解决第一个错误,也不是第二个错误,如果片段被替换,而 onPostExecute()执行)
  • 检查是否 getActivity()或呼叫 this.isDetached()(不是一个真正的修复和我需要检查它,每当我称之为 getActivity()等)
  • Calling cancel method on my AsyncTask (won't fix first error nor the second error if the fragment is replaced while onPostExecute() is executed)
  • checking if getActivity() is null or calling this.isDetached() (not a real fix and I'd need to check it whenever I call getActivity() and so on)

所以我的问题是:什么是最好的摆脱这些AsyncTask的问题?使用活动我没有这些问题,因为它们没有封杀/分离选项卡上的变化(这导致更高的内存使用情况 - 我为什么要切换到碎片的原因)

So my question is: what would be the best to get rid of these AsyncTask problems? I did not have these problems using Activities as they weren't "killed" / detached on tab change (which resulted in higher memory usage - the reason why I like to switch to Fragments)

推荐答案

由于的AsyncTask 在后台运行,您的片段可能成为其父活动的时间分离它完成。当你找到了,你可以使用 isDetached()检查。这没有什么错,你不必检查每一个时间,只考虑片段和活动生命周期。

Since AsyncTask is running in the background, your fragment may become detached from its parent activity by the time it finishes. As you've found out, you can use isDetached() to check. There's nothing wrong with that, and you don't have to check every time, just consider the fragment and activity life cycles.

另外两个备选方案:

  • 使用装载机,他们的目的是发挥更好的与片段
  • 将您的AsyncTask加载到父活动,并使用接口与碎片分离。该活动将知道一个片段是否存在与否,并采取相应的行动(通过可能丢弃,如果该片段消失的结果)。

这篇关于被替换片段,而AsyncTask的执行 - NullPointerException异常的getActivity()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆