commitAllowingStateLoss() in fragment activities

CQM picture CQM · Jun 19, 2013 · Viewed 36.8k times · Source

my app uses fragment activities, it is in portrait mode only and there is no way to rotate the screen.

Originally I was using the commit() method but now I plan to indiscriminately change these to commitAllowingStateLoss() for the fragment activities

Is there any reason not to indiscriminately do this without re-evaluating each individual case where I use a fragment?

Answer

IanB picture IanB · Jul 8, 2013

If I understand correctly you mean : Is there any reason NOT to indiscriminately do this without re-evaluating each individual case where I use a fragment?

The answer is Yes - you should not do this without carefully re-evaluating each individual case where you use a fragment.

Of course, by preventing restarts due to config changes (screen rotations) you have eliminated one of the key problem areas : i.e. the user could rotate the screen AFTER a call to onSaveInstanceState but BEFORE the commitAllowingStateLoss. In this case a fragment or portion of UI might be lost. For an informal discussion of this, see this post.

But there are other situations you should consider before replacing commit by commitAllowingStateLoss.

  1. Basically, any UI updates between onSaveInstanceState and the commitAllowingStateLoss: Android: IllegalStateException - When is it thrown?

  2. If you have any headless fragments that update the UI of your activity then some of their updates might be lost (see this article).

  3. Android might "kill" a fragment because the phone/tab is running low on resources (see this answer).

Of course, if screen rotations are prevented, then onSaveInstanceState may not be called, in which case the window of opportunity for an update to be lost is increased.

If you do decide to use commitAllowingStateLoss then are things you can do to minimize the risks involved: e.g. consider doing a commit / executePendingTransactions when the parent activity is next restarted (I know you don't want to do this, but someone else might read this).

Finally (again in case someone else reads this - this is not relevant in your case) there are probably safer ways of handling an IllegalStateException than moving from commit to commitAllowStateLoss. e.g you could just stick with commit and handle the IllegalStateException. Alternatively, you may have hit a bug in Android and there might be a workaround.