Android 异常java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

释放双眼,带上耳机,听听看~!

项目中发现重复跳转一个Fragment出现改异常

  Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1489)
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1507)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:634)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:613)

这个问题是在使用FragmentTransaction的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.
*
* <p class="note">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 {@link #commitAllowingStateLoss()} for
* situations where it may be okay to lose the commit.</p>
*
* @return Returns the identifier of this transaction's back stack entry,
* if {@link #addToBackStack(String)} had been called.  Otherwise, returns
* a negative number.
*/
public abstract int commit();
/**
* Like {@link #commit} but allows the commit to be executed after an
* activity's state is saved.  This is dangerous because the commit can
* be lost if the activity needs to later be restored from its state, so
* this should only be used for cases where it is okay for the UI state
* to change unexpectedly on the user.
*/
public abstract int commitAllowingStateLoss();

上面2个方法得大概意思是说我使用的 commit方法是在Activity的onSaveInstanceState()之后调用的,这样会出错,因为onSaveInstanceState方法是在该Activity即将被销毁前调用,来保存Activity数据的,如果在保存玩状态后再给它添加Fragment就会出错。if the activity needs to be restored from its state. See {@link #commitAllowingStateLoss()} 。so,把commit换成commitAllowingStateLoss()运行就解决了该bug,记录一下。

人已赞赏
Android文章

Android查看apk包的SHA1码

2021-1-7 10:01:26

Android文章

Android Studio获取sha1值和MD5的正确姿势

2021-1-7 10:59:07

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索