Fragments remain after Activity get's killed and recreated

Towlie288 picture Towlie288 · May 16, 2013 · Viewed 15k times · Source

I have a FragmentActivity (Support Fragments) where I create Fragments by code and put them into FrameLayouts. It all works fine so far. Now if I leave the App an return everything is fine as long as the system doesn't kill my Activity (or I do that with the stop button in DDMS). If that happens nothing get's called and my Activity gets killed. onDestroy is not called.

So when I reopen my App all of the Fragments still exist and I get NullPointerExeptions because they try to do their work. The Fragments are not supposed to exist in this state of the App so that's problem for me.

I don't need them in the backStack so I don't put them there and cant call popBackStack() to get rid of them.

How can I reset my FragmentManager in onCreate() or just make sure that the Fragments get destroyed as well?

Answer

stan0 picture stan0 · Feb 19, 2014

The fragment's lifecycle is similar to the activity's lifecycle so it can be killed and recreated by the system in order to save memory for other apps. This means that there is a mechanism for saving and restoring the fragment's state. You should use it.

If it's impossible to save the fragment's state (due to its data being dynamic and non serializable), try to implement some default behavior for non initialized state.