转自:http://www.androiddesignpatterns.com/2013/08/fragment-transaction-commit-state-loss.html

The following stack trace and exception message has plagued StackOverflow ever since Honeycomb's initial release:

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1341)
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1352)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:595)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:574)

This post will explain why and when this exception is thrown, and will conclude with several suggestions that will help ensure it never crashes your application again.

Why was the exception thrown?

The exception was thrown because you attempted to commit a FragmentTransaction after the activity's state had been saved, resulting in a phenomenon known as Activity state loss. Before we get into the details of what this actually means, however, let's first take a look at what happens under-the-hood when onSaveInstanceState() is called. As I discussed in my last post about Binders & Death Recipients, Android applications have very little control over their destiny within the Android runtime environment. The Android system has the power to terminate processes at any time to free up memory, and background activities may be killed with little to no warning as a result. To ensure that this sometimes erratic behavior remains hidden from the user, the framework gives each Activity a chance to save its state by calling its onSaveInstanceState() method before making the Activity vulnerable to destruction. When the saved state is later restored, the user will be given the perception that they are seamlessly switching between foreground and background activities, regardless of whether or not the Activity had been killed by the system.

When the framework calls onSaveInstanceState(), it passes the method a Bundle object for the Activity to use to save its state, and the Activity records in it the state of its dialogs, fragments, and views. When the method returns, the system parcels the Bundle object across a Binder interface to the System Server process, where it is safely stored away. When the system later decides to recreate the Activity, it sends this same Bundle object back to the application, for it to use to restore the Activity's old state.

So why then is the exception thrown? Well, the problem stems from the fact that these Bundle objects represent a snapshot of an Activity at the moment onSaveInstanceState() was called, and nothing more. That means when you call FragmentTransaction#commit() after onSaveInstanceState() is called, the transaction won't be remembered because it was never recorded as part of the Activity's state in the first place. From the user's point of view, the transaction will appear to be lost, resulting in accidental UI state loss. In order to protect the user experience, Android avoids state loss at all costs, and simply throws an IllegalStateException whenever it occurs.

When is the exception thrown?

If you've encountered this exception before, you've probably noticed that the moment when it is thrown is slightly inconsistent across different platform versions. For example, you probably found that older devices tended to throw the exception less frequently, or that your application was more likely to crash when using the support library than when using the official framework classes. These slight inconsistencies have led many to assume that the support library is buggy and can't be trusted. These assumptions, however, are generally not true.

The reason why these slight inconsistencies exist stems from a significant change to the Activity lifecycle that was made in Honeycomb. Prior to Honeycomb, activities were not considered killable until after they had been paused, meaning that onSaveInstanceState() was called immediately beforeonPause(). Beginning with Honeycomb, however, Activities are considered to be killable only after they have been stopped, meaning that onSaveInstanceState() will now be called before onStop() instead of immediately before onPause(). These differences are summarized in the table below:

  pre-Honeycomb post-Honeycomb
Activities can be killed before onPause()? NO NO
Activities can be killed before onStop()? YES NO
onSaveInstanceState(Bundle) is guaranteed to be called before... onPause() onStop()

As a result of the slight changes that were made to the Activity lifecycle, the support library sometimes needs to alter its behavior depending on the platform version. For example, on Honeycomb devices and above, an exception will be thrown each and every time a commit() is called afteronSaveInstanceState() to warn the developer that state loss has occurred. However, throwing an exception every time this happened would be too restrictive on pre-Honeycomb devices, which have their onSaveInstanceState() method called much earlier in the Activity lifecycle and are more vulnerable to accidental state loss as a result. The Android team was forced to make a compromise: for better inter-operation with older versions of the platform, older devices would have to live with the accidental state loss that might result between onPause() and onStop(). The support library's behavior across the two platforms is summarized in the table below:

  pre-Honeycomb post-Honeycomb
commit() before onPause() OK OK
commit() between onPause() and onStop() STATE LOSS OK
commit() after onStop() EXCEPTION EXCEPTION

How to avoid the exception?

Avoiding Activity state loss becomes a whole lot easier once you understand what is actually going on. If you've made it this far in the post, hopefully you understand a little better how the support library works and why it is so important to avoid state loss in your applications. In case you've referred to this post in search of a quick fix, however, here are some suggestions to keep in the back of your mind as you work with FragmentTransactions in your applications:

  • Be careful when committing transactions inside Activity lifecycle methods. A large majority of applications will only ever commit transactions the very first time onCreate() is called and/or in response to user input, and will never face any problems as a result. However, as your transactions begin to venture out into the other Activity lifecycle methods, such as onActivityResult(),onStart(), and onResume(), things can get a little tricky. For example, you should not commit transactions inside the FragmentActivity#onResume() method, as there are some cases in which the method can be called before the activity's state has been restored (see the documentation for more information). If your application requires committing a transaction in an Activity lifecycle method other than onCreate(), do it in either FragmentActivity#onResumeFragments() orActivity#onPostResume(). These two methods are guaranteed to be called after the Activity has been restored to its original state, and therefore avoid the possibility of state loss all together. (As an example of how this can be done, check out my answer to this StackOverflow question for some ideas on how to commit FragmentTransactions in response to calls made to theActivity#onActivityResult() method).

  • Avoid performing transactions inside asynchronous callback methods. This includes commonly used methods such as AsyncTask#onPostExecute() andLoaderManager.LoaderCallbacks#onLoadFinished(). The problem with performing transactions in these methods is that they have no knowledge of the current state of the Activity lifecycle when they are called. For example, consider the following sequence of events:

    1. An activity executes an AsyncTask.
    2. The user presses the "Home" key, causing the activity's onSaveInstanceState() and onStop()methods to be called.
    3. The AsyncTask completes and onPostExecute() is called, unaware that the Activity has since been stopped.
    4. FragmentTransaction is committed inside the onPostExecute() method, causing an exception to be thrown.

    In general, the best way to avoid the exception in these cases is to simply avoid committing transactions in asynchronous callback methods all together. Google engineers seem to agree with this belief as well. According to this post on the Android Developers group, the Android team considers the major shifts in UI that can result from committing FragmentTransactions from within asynchronous callback methods to be bad for the user experience. If your application requires performing the transaction inside these callback methods and there is no easy way to guarantee that the callback won't be invoked after onSaveInstanceState(), you may have to resort to usingcommitAllowingStateLoss() and dealing with the state loss that might occur. (See also these two StackOverflow posts for additional hints, here and here).

  • Use commitAllowingStateLoss() only as a last resort. The only difference between callingcommit() and commitAllowingStateLoss() is that the latter will not throw an exception if state loss occurs. Usually you don't want to use this method because it implies that there is a possibility that state loss could happen. The better solution, of course, is to write your application so thatcommit() is guaranteed to be called before the activity's state has been saved, as this will result in a better user experience. Unless the possibility of state loss can't be avoided,commitAllowingStateLoss() should not be used.

Hopefully these tips will help you resolve any issues you have had with this exception in the past. If you are still having trouble, post a question on StackOverflow and post a link in a comment below and I can take a look. :)

As always, thanks for reading, and leave a comment if you have any questions. Don't forget to +1 this blog and share this post on Google+ if you found it interesting!

Fragment Transactions & Activity State Loss的更多相关文章

  1. Fragment提交transaction导致state loss异常

    下面自从Honeycomb发布后,下面栈跟踪信息和异常信息已经困扰了StackOverFlow很久了. java.lang.IllegalStateException: Can not perform ...

  2. Fragment Transactions和Activity状态丢失

    本文由 伯乐在线 - 独孤昊天 翻译.未经许可,禁止转载!英文出处:androiddesignpatterns.欢迎加入翻译组. 下面的堆栈跟踪和异常代码,自从Honeycomb的初始发行版本就一直使 ...

  3. Fragment、Activity 保存状态

    Activity 保存状态1. void onCreate(Bundle savedInstanceState) 当Activity被第首次加载时执行.我们新启动一个程序的时候其主窗体的onCreat ...

  4. Fragment 与Activity

    一个Activity 对应 多个Fragment; 每一个类 extends Fragment , 一个Activity 可以同时显示多个 Fragment; Fragment是依赖于Activity ...

  5. Fragment与Activity之间的通信

      我个人将Fragment与Activity间的通信比喻为JSP与Servlet间的通信,fragment中用接口的方式来进行与Activity的通信.通信的结果可以作为数据传入另一个Fragmen ...

  6. Android系列之Fragment(三)----Fragment和Activity之间的通信(含接口回调)

    ​[声明] 欢迎转载,但请保留文章原始出处→_→ 生命壹号:http://www.cnblogs.com/smyhvae/ 文章来源:http://www.cnblogs.com/smyhvae/p/ ...

  7. 深入分析:Fragment与Activity交互的几种方式(一,使用Handler)

    这里我不再详细介绍那写比较常规的方式,例如静态变量,静态方法,持久化,application全局变量,收发广播等等. 首先我们来介绍使用Handler来实现Fragment与Activity 的交互. ...

  8. Fragment和Activity的区别

    Fragment用来描述一些行为或一部分用户界面在一个Activity中,可以合并多个Fragment在一个单独的Activity中建立多个UI面板,同时重用Fragment在多个activity中. ...

  9. Fragment 与 Activity 通信

    先说说背景知识: (From:http://blog.csdn.net/t12x3456/article/details/8119607) 尽管fragment的实现是独立于activity的,可以被 ...

随机推荐

  1. How to return plain text from AWS Lambda & API Gateway

    With limited experience in AWS Lambda & API Gateway, it's struggling to find the correct way to ...

  2. C/C++有效对齐值的确定

    先来看看什么是对齐.现代计算机中内存空间都是按照字节(byte)划分的,从理论上讲似乎对任何类型的变量的访问可以从任何地址开始,但实际情况是在访问特定变量的时候经常在特定的内存地址访问,这就需要各类型 ...

  3. .NetCore 结合微服务项目设计总结下实践心得

    以下内容全是在项目中的体验,个人理解心得 起源 2017年7月开始接触.NetCore,当时还是因为Idr4的原因,之前的项目都是用的Idr3做,后面接触到Idr4后,决定以后所有项目都使用.NetC ...

  4. 【LOJ】#2546. 「JSOI2018」潜入行动

    题解 dp[i][j][0/1][0/1]表示以\(i\)为根的子树,用了\(j\)个,i点选了或者没选,i点被覆盖或没被覆盖 转移比较显然,但是复杂度感觉不太对? 其实转移到100个的时候就使第二维 ...

  5. 远程登陆linux连接mysql root账号报错:2003-can't connect to MYSQL serve(转)

    远程连接mysql root账号报错:2003-can't connect to MYSQL serve 1.远程连接Linux系统,登录数据库:mysql -uroot -p(密码) 2.修改roo ...

  6. 关于IEnumerator<T>泛型枚举器 和 IEnumerable<T>

    在开发中我们经常会用到 IEnumerable<T> xxx 或者 List<T> xxx 这种集合或者集合接口,实际上就是一个线性表嘛然后结合C#提供的语法糖 foreach ...

  7. C# EF Attach 与 Entry

    先了解一下 EF 框架的 EntityState 在使用EF框架时, 我们通常都是通过调用 SaveChanges() 方法把增加/修改/删除的数据提交到数据库,但是上下文是如何知道实体对象是增加.修 ...

  8. js原型鏈與js繼承解析

    最近在網上看了諸多js原型鏈的解析,說得雲裡霧裡,不明所以.徹底了解後,決定出個博客記錄一下,一是方便後來人學習,二是方便日後複習. 首先,我們來看一下構造函數.原型.實例之間的關係圖: 所以,我們通 ...

  9. 图的遍历 之 深搜dfs

    DFS 遍历 深度优先搜索是一个递归过程,有回退过程. 对一个无向连通图,在访问图中某一起始顶点u 后,由u 出发,访问它的某一邻接顶点v1:再从v1 出发,访问与v1 邻接但还没有访问过的顶点v2: ...

  10. Xtreme8.0 - Kabloom dp

    Xtreme8.0 - Kabloom 题目连接: https://www.hackerrank.com/contests/ieeextreme-challenges/challenges/kablo ...