62

I was using the commit method in my project that built it with fragments.

Anyway, sometimes I was getting IllegalStateException: Can not perform this action after onSaveInstanceState error and I couldn't find any good solution about it but just this method commitAllowingStateLoss(). I changed commit function to commitAllowingStateLoss() but didn't use it long time to test so may this function help me? And the main question, what is the difference between commit() and commitAllowingStateLoss()?

tttony
  • 4,944
  • 4
  • 26
  • 41
Mert Aydin
  • 621
  • 1
  • 6
  • 7

2 Answers2

110

There is only one difference between commit() and commitAllowingStateLoss(): the latter doesn't throw an exception if state loss occurs. Other than that, they have identical behavior.

See my blog post about this topic for more information.

Alex Lockwood
  • 83,063
  • 39
  • 206
  • 250
  • 1
    The difference is more subtle than that. `commit()` can throw an exception event if state loss would not occur. For example, `commit()` always throws an exception when called from `LoaderCallbacks.onLoadFinished()`, even in circumstances where `commitAllowingStateLoss()` saves transaction without state loss. Of course, _sometimes_ state cannot be saved when handling `onLoadFinished()`. – Juozas Kontvainis Jul 20 '16 at 11:20
4

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.

commitAllowingStateLoss():

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.

If you do commit() after onSaveInstance(), you will get below exception:

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)
Jitesh Mohite
  • 31,138
  • 12
  • 157
  • 147