java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.app.ActivityThread.deliverResults(ActivityThread.java:3724)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3767)
at android.app.ActivityThread.access$1500(ActivityThread.java:153)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1418)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:5462)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)
Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1842)
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1860)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:649)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:609
at android.app.Activity.dispatchRequestPermissionsResult(Activity.java:6634)
at android.app.Activity.dispatchActivityResult(Activity.java:6512)
at android.app.ActivityThread.deliverResults(ActivityThread.java:3720)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:3767)?
at android.app.ActivityThread.access$1500(ActivityThread.java:153)?
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1418)?
at android.os.Handler.dispatchMessage(Handler.java:102)?
at android.os.Looper.loop(Looper.java:154)?
at android.app.ActivityThread.main(ActivityThread.java:5462)?
at java.lang.reflect.Method.invoke(Native Method)?
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:739)?
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:629)?
最终看到了关键所在,”Can not perform this action after onSaveInstanceState”,就是说不在保存状态之后去进行”this action”,”this action”指的就是下边的FragmentManager的commint()方法。我们都知道,FragmentManager开启事物最后都要提交:
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.fragmentContainer, new MyFragment(), String.valueOf(0));
transaction.commit();
通过查看FragmentManager的commit()官方文档我们可以看到:
Schedules a commit of this transaction. The commit does not happen immediately;
it will be scheduled as work on the main thread to be done the next time that thread is ready.
A transaction can only be committed with this method prior to its containing activity saving its state.
If the commit is attempted after that point, an exception will be thrown. This is because the state after
the commit can be lost if the activity needs to be restored from its state. See commitAllowingStateLoss()
for situations where it may be okay to lose the commit.