0

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?

htafoya
  • 18,261
  • 11
  • 80
  • 104
  • "the fragment cannot be recreated because it is linked to some non-serializable data" -- hold that data in something that survives configuration changes, such as a Jetpack `ViewModel` or a repository singleton. – CommonsWare Sep 30 '22 at 19:07
  • That is not the question, i want to avoid recreating it. ViewModel doesn't survive an Activity being recreated if it is because of memory situations, Singleton is not a good approach because the referenced object won't even be relevant anymore. – htafoya Sep 30 '22 at 19:26

1 Answers1

0

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.

htafoya
  • 18,261
  • 11
  • 80
  • 104