Search code examples
onactivityresult

the destroyed fragment onActivityResult is called instead of the re-started fragment


Having problem that the onActivityResult in the destroyed fragment is still called.

The OS could destroy the activity for some reason (i.e. activity goes to background and with low memory, not only the configuration change). In my test case it has a activity/fragment to start the camera activity, when the camera view is up the os may destroy the lunching fragment (one easier way to make it happens is to check the "Don't keep activities" in Developer option settings (but you don't have to, the destroy may happen for some reasons the os decides to do so).

It is similar to the problem of Android: Activity getting Destroyed after calling Camera Intent

But the here difference is The Fragment F1 opened the camera activity. F1's onDestroy is called by os. After took photo from camera activity and back to the lunching fragment the os recreates it but it is a new instance F2 of the fragment.

The trace shows the onActivityResult on fragment instance F1 is still get called with the new photo data, but the fragment instance F2's onActivityResult is not called.

Is this common problem when the destroy/recreate by os? How to catch the callback from the opened activity (like camera in this case) and pass the data to the os newly created fragment instance?

Thanks!


Solution

  • I think the problem is that when os re-create the activity at onCreate(Bundle savedInstanceState), we should check savedInstanceState to not to recreate a extra new Fragment instance ourself. Let the os does the re-creation of the Fragment instance. Then the onActivityResult() is called on the proper Fragment instance.