androidandroid-fragmentsandroid-lifecycleandroid-dialogfragmentfragment-lifecycle

Detach Fragment when Activity gets recreated


When the activity gets recreated due to config-change or memory issues when in stack (going back to the activity stack) the attached fragment gets recreated as well.

In my case, the fragment cannot be recreated because it is linked to some non-serializable data that cannot be simply reassigned (refactored) on the lifecycle methods. So the app crashes due to unitialized properties in the Fragment.

The Fragment with this issue is a DialogFragment that could simply be ignored and closed instead of be recreated and shown again. How could I remove the fragment in the case the activity gets destroyed?


Solution

  • What I did was to manually remove the fragment (if found) from activity before activity is destroyed. This only works for me because the fragment is a dialog which I don't care if it cannot be recovered.

    I couldn't find any other way to automatically detach it with simple configurations.