Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it safe to commit a FragmentTransaction?

According to the docs

A fragment transaction can only be created/committed prior to an activity saving its state. If you try to commit a transaction after Activity.onSaveInstanceState() (and prior to a following Activity.onStart or Activity.onResume(), you will get an error.

I can understand that the first part that a fragment transaction can't committed after Activity.onSaveInstanceState(), because the state after the commit can be lost if the activity needs to be restored.

But I don't understant why we can't commit a fragment transaction prior to a Activity.onStart or Activity.onResume()? Oncreate() is also prior to Activity.onStart or Activity.onResume().Does it mean that we can't even commit it in oncreate()?

like image 227
user3591494 Avatar asked Nov 08 '16 15:11

user3591494


1 Answers

The key here is that you can't commit a transaction after a call to onSaveInstanceState() and prior to a following onStart() or onResume().

You can commit transactions just fine on the initial onCreate() and a subsequent onStart() or onResume() because there is no state.

However, if the Activity is restoring its state (i.e. onSaveInstanceState() was previously called, and the Activity is recreating itself with that state, you cannot perform a Fragment transaction. This is because if you commit a Fragment transaction prior to the Activity restoring the previous Fragment state, you end up in a situation where it is unclear what state you are in. Does the saved state take precedence over the new state that you have created by committing a Fragment transaction, or should the new transaction take precedence over the saved state?

The easiest way to check for this scenario is to check if the savedInstanceState bundle passed to onCreate() and other lifecycle methods is null. If it's null, there is no saved state and you are safe to perform your transaction. If it is not null, then there is saved state that you probable want to preserve.

like image 182
Bryan Herbst Avatar answered Oct 03 '22 01:10

Bryan Herbst