Fragment's onSaveInstanceState() is never called

AndroidAndroid Fragments

Android Problem Overview


I'm trying to save data in a Fragment's onSaveInstanceState(), but the method is never called.

Can someone help?

public class MyFragment extends Fragment {
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        ScrollView content = (ScrollView) inflater.inflate(R.layout.content, container, false);
        // More stuff
        return content;
    }
    
    @Override
    public void onSaveInstanceState(Bundle icicle) {
        // NEVER CALLED
        super.onSaveInstanceState(icicle);
        //More stuff
    }
    
}

Android Solutions


Solution 1 - Android

I finally figured out the problem, at least in my case. I had an overridden onSaveInstanceState in my FragmentActivity that did not call super.onSaveInstanceState(Bundle outState). Once I added that in, the Fragment.onSaveInstanceState(Bundle outState) functioned normally.

Solution 2 - Android

I encountered the same question with you, and tried onSaveInstanceState() method, but did not work.

I think onSaveInstanceState() only works for the scenario that user jumps from one activity to another activity and back, it does not work in the scenario that user jumps among fragments in the same activity.

here is the guide document from Google. http://developer.android.com/guide/components/tasks-and-back-stack.html#ActivityState

Solution 3 - Android

In some situations you might find it helpful to use fragment arguments instead of savedInstanceState. Further explanation.

Solution 4 - Android

One thing to check is to make sure the Activity that contains the fragment is not preventing a restart by including the android:configChanges flag in the AndroidManifest.xml.

Solution 5 - Android

Try calling FragmentManager#saveFragmentInstanceState and Fragment#setInitialSavedState in Activity. You call saveFragmentInstanceState, then framework will call onSaveInstanceState. And you call setInitialSavedState, then framework will call onCreateView with no null argument 'Bundle savedInstanceState'.

Solution 6 - Android

Try calling setRetainInstance(true) in onCreate(Bundle savedInstanceState).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjulView Question on Stackoverflow
Solution 1 - AndroidJamesView Answer on Stackoverflow
Solution 2 - AndroidZephyrView Answer on Stackoverflow
Solution 3 - AndroidFyodor VolchyokView Answer on Stackoverflow
Solution 4 - AndroidScottView Answer on Stackoverflow
Solution 5 - AndroidYossieView Answer on Stackoverflow
Solution 6 - AndroidFelixView Answer on Stackoverflow