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?
As Fragment is embedded inside an Activity, it will be killed when Activity is killed. As contents of activity are first killed, fragment will be destroyed just before activity gets destroyed.
Various Android system operations can affect the state of your fragment. To ensure the user's state is saved, the Android framework automatically saves and restores the fragments and the back stack. Therefore, you need to ensure that any data in your fragment is saved and restored as well.
To remove (so destroy) these fragments, you can call: You need to use findFragmentById for Fragment from XML file. And then find this in the MainActivity on click listener. I've added this to the OnClickListener but it always returns 'null' for the fragment I want to remove.
The first key is that we can save our Fragments' state ourselves using FragmentManager. saveInstanceState(Fragment) . Before removing the Fragment, call this method to get a Bundle containing your Fragment's saved state! The second key is restoring state.
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.
onSaveInstanceState
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With