【发布时间】:2015-06-12 16:39:07
【问题描述】:
Stackoverflow 中有很多关于使用 getActivity()==null 检查片段中的活动是否为空的问题已得到解答
如何检查活动本身的活动是否不为空?
我的具体情况是这样的:
activity启动一个asynctask,然后activity被销毁,然后asynctask在onPostExecute中返回,它调用activity中的一个方法(它被注册为该任务的监听器)并且这个方法使用对THIS的引用来传递一个上下文一个方法。但是,上下文为空。
编辑:这是一些代码。
public interface OnGetStuffFromServerListener {
void onGetStuffSuccess();
}
public class SomeActivity implements OnGetStuffFromServerListener {
@Override
public whatever onCreate() {
new GetStuffFromServer(this).execute();
}
@Override
public void onGetStuffFromServerSuccess() {
deleteSomeFiles(this); // NPE -> How do I check if activity still exists here?
}
private void deleteSomeFiles(Context context) {
...
context.getExternalFilesDir(null).toString(); // NPE toString on a null object reference
}
}
public class GetSomeStuffFromServer extends AsyncTask<Void, Void, Void> {
private OnGetSomeStuffFromServerListener listener;
public GetSomeStuffFromServer (OnGetSomeStuffFromServerListener listener) {
this.listener = listener;
}
...doInBackground
onPostExecute() {
if(listener!=null) {
listener.onGetSomeStuffFromServerSuccess();
}
}
}
实际上,如果我使用 getApplicationContext() 而不是这个,也许我根本不会有问题?
【问题讨论】:
-
你为什么使用 asynctask 而不是 asynctaskloader? stackoverflow.com/questions/7120813/…
-
这是一个不同的问题。我正在修复别人的代码,现在无法重写他们的应用程序 :)
-
发布一些示例代码,说明您要描述的内容以及问题所在。
-
这永远不会为空。错误不是内容为空,而是文件目录为空。 toString 是在归档目录而不是上下文上调用的。
-
我不认为你的活动是空的,因为你正在泄漏它。实际的 null 是 context.getExternalFilesDir(null) 的结果
标签: android