在Stackoverflow上有很多关于从片段检查活动是否为null的已回答问题,使用
我的具体情况是:
活动启动一个异步任务,然后销毁活动,然后asynctask在onPostExecute中返回,它调用活动中的一个方法(该方法作为该任务的侦听器注册),并且此方法使用对THIS的引用来传递方法中的上下文。但是上下文为null。
编辑:这里是一些代码。
getActivity()==null
如何在活动本身中检查活动是否不为null?我的具体情况是:
活动启动一个异步任务,然后销毁活动,然后asynctask在onPostExecute中返回,它调用活动中的一个方法(该方法作为该任务的侦听器注册),并且此方法使用对THIS的引用来传递方法中的上下文。但是上下文为null。
编辑:这里是一些代码。
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()而不是this,也许就不会有任何问题了?