您的位置:首页 > 移动开发 > Android开发

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

2013-07-05 00:08 375 查看
做项目的时候用到fragment,在fragment快速切换的时候发生了异常:IllegalStateException: Can not perform this action after onSaveInstanceState

logcat的提示信息: Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState


这个异常是由于在使用FragmentTransition的 commit方法添加一个Fragment的时候出现的



public abstract int 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.

Returns
Returns the identifier of this transaction's back stack entry, if 
addToBackStack(String)
 had
been called. Otherwise, returns a negative number.

开始我用的是这个方法,fragment切换的时候基本上都会用这个方法。以前用的时候没出错,这次却不行了。在commit()方法的后边还有个方法:



public abstract int commitAllowingStateLoss ()

Like 
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.
这个方法与commit()一样,但是允许在activity的状态信息保存后调用。用这个方法是不安全的,有可能activity还没恢复呢就不执行commit方法了。所以这个方法只能用在ui状态转换意外的时候

比较两个方法的不同就可以知道,我调用的 commit方法是在Activity的onSaveInstanceState()之后调用的。onSaveInstanceState方法是在该Activity即将被销毁前调用,来保存Activity数据的,如果在保存完状态后

再给它添加Fragment就会出错。解决办法就是把commit()方法替换成 commitAllowingStateLoss()就行

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  异常 Android 安全 UI
相关文章推荐