参考:
Fragment的展现与Activity状态丢失 IllegalStateException:Can not perform this action after onSaveInstanceState
解决 IllegalStateException: Can not perform this action after onSaveInstanceState
异常:
java.lang.IllegalStateException
Can not perform this action after onSaveInstanceState
解析原始
1 android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1493)
2 android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1511)
3 android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:634)
4 android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:613)
5 com.dch.dai.activity.lend.ManualLendDetailOneActivity.initFragment(ManualLendDetailOneActivity.java:78)
6 com.dch.dai.activity.lend.ManualLendDetailOneActivity.access$(ManualLendDetailOneActivity.java:29)
7 com.dch.dai.activity.lend.ManualLendDetailOneActivity$2.onPostExecute(ManualLendDetailOneActivity.java:152)
8 com.dch.dai.utils.http.MyAsyncTask.onPostExecute(MyAsyncTask.java:38)
9 com.dch.dai.utils.http.MyAsyncTask.onPostExecute(MyAsyncTask.java:9)
10 android.os.AsyncTask.finish(AsyncTask.java:660)
11 android.os.AsyncTask.-wrap1(AsyncTask.java)
12 android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:677)
13 android.os.Handler.dispatchMessage(Handler.java:102)
14 android.os.Looper.loop(Looper.java:)
15 android.app.ActivityThread.main(ActivityThread.java:6343)
16 java.lang.reflect.Method.invoke(Native Method)
17 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:920)
18 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:810)
分析:
onSaveInstanceState方法是在该Activity即将被销毁前调用,来保存Activity数据的,如果在保存完状态后
再给它添加Fragment就会出错。
解决办法
1、就是把commit()方法替换成 commitAllowingStateLoss()
getSupportFragmentManager().beginTransaction()
.remove(getSupportFragmentManager().findFragmentById(R.id.fl_main))
.commit();
getSupportFragmentManager().beginTransaction()
.remove(getSupportFragmentManager().findFragmentById(R.id.fl_main))
.commitAllowingStateLoss();
2、判断activity是否已finish,没有则执行
//判断Activity是否Destroy
protected boolean isDestroy(Activity activity) {
return activity == null ||
activity.isFinishing() ||
(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && activity.isDestroyed());
}