When Is It Safe To Commit A Fragmenttransaction?
Solution 1:
The key here is that you can't commit a transaction after a call to onSaveInstanceState()
and prior to a followingonStart()
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.
Solution 2:
It's safe any time beforeonSaveInstanceState()
, which essentially means before onPause()/onResume()
, and if your Activity ever went to onPause()
, then it's safe only after onResume()
.
For example, during onActivityResult()
, you haven't actually gone to after onResume()
, so opening a dialog in onActivityResult()
can crash.
Solution 3:
Might want to bear in mind a committed transaction might not have executed. This handles that:
getSupportFragmentManager().executePendingTransactions();
Post a Comment for "When Is It Safe To Commit A Fragmenttransaction?"