Years ago, I ran into a problem in one of my apps when I tried to commit a FragmentTransaction
inside my onActivityResult()
callback. Googling around, I found this question and answer, which say
At the time that
onActivityResult()
is called, the activity/fragment's state may not yet have been restored, and therefore any transactions that happen during this time will be lost as a result.
I wound up adapting the solution recommended in the same answer for my app, and life was good. However, recent experimentation shows that perhaps things have changed, and it may now be safe to commit a FragmentTransaction
from inside onActivityResult()
.
The documentation for (support v4) FragmentManager.beginTransaction()
defines the safe window for transactions as:
Note: A fragment transaction can only be created/committed prior to an activity saving its state. If you try to commit a transaction after
FragmentActivity.onSaveInstanceState()
(and prior to a followingFragmentActivity.onStart
orFragmentActivity.onResume()
, you will get an error.
Reading the documentation for onActivityResult()
, I see
You will receive this call immediately before
onResume()
when your activity is re-starting.
This leads me to believe that it should be safe to execute these transactions in onActivityResult()
, as onStart()
will have already been called, putting me inside the safe window.
I made an app to test this out, and I'm successfully seeing dialog fragments that I create and commit inside onActivityResult()
. I had the same app also log the activity lifecycle callbacks so I could inspect their order, and I see onStart()
, then onRestoreInstanceState()
, and then onActivityResult()
every time.
Am I missing something? Or has the framework changed and onActivityResult()
is now guaranteed to be a safe place for fragment transactions? Does this behavior vary by API level?
I found another question and answer that seems to read the documentation the same way I have, but both are over a year old and neither specifically refers to onActivityResult()
as a safe place for transactions.