Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fragments remain after Activity get's killed and recreated

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?

like image 771
Towlie288 Avatar asked May 16 '13 14:05

Towlie288


People also ask

What happens to fragment when activity is destroyed?

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.

How to retain fragment state android?

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.

How do I destroy fragments after replace?

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.

How to save and restore fragment state android?

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.


1 Answers

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.

  • Save the state of the fragment in onSaveInstanceState
  • Restore the state - the savedState bundle is provided to the fragment in multiple methods (onCreate, onCreateView, etc.)

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.

like image 191
stan0 Avatar answered Oct 07 '22 12:10

stan0