在 Stackoverflow 中有很多关于使用 getActivity()==null
检查 fragment 中的 Activity 是否为 null 的已回答问题
如何检查 Activity 本身是否为空?
我的具体情况是这样的:
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() 而不是它,也许我根本不会有问题?
最佳答案
我不确定为什么要销毁您的 Activity。尽管您可以使用 Bundle 重新创建 Activity。谷歌的documentation on Activities 提供了以下用于保存和恢复 Activity 实例的示例。
以下将保存您的 Activity 状态:
static final String STATE_SCORE = "playerScore";
static final String STATE_LEVEL = "playerLevel";
...
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(STATE_SCORE, mCurrentScore);
savedInstanceState.putInt(STATE_LEVEL, mCurrentLevel);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
以下将被调用以恢复您的 Activity 之前的状态。请注意,逻辑包含在 onCreate() 中,因此听起来您将再次初始化 Activity。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Always call the superclass first
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
} else {
// Probably initialize members with default values for a new instance
}
...
}
如果有帮助,请告诉我!
编辑:
尝试取消 onDestroy() 中的操作。如果 Activity 已调用 onDestroy(),则其内存已被设备释放。确保您没有在代码中的其他任何地方处理您的 Activity。
@Override
protected void onDestroy() {
asynctask.cancel(true);
super.onDestroy();
}
关于Android 检查此 Activity 是否不为空/已销毁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30808154/