jul
jul

Reputation: 37464

Fragment's onSaveInstanceState() is never called

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
    }

}

Upvotes: 69

Views: 55778

Answers (7)

DECEMD
DECEMD

Reputation: 1

just restore Bundle in onCreate not in onCreateView

Upvotes: 0

Fyodor Volchyok
Fyodor Volchyok

Reputation: 5673

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

Upvotes: 9

Zephyr
Zephyr

Reputation: 6341

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

Upvotes: 34

Yossie
Yossie

Reputation: 1

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'.

Upvotes: -1

James
James

Reputation: 1756

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.

Upvotes: 70

Scott
Scott

Reputation: 1313

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.

Upvotes: 6

Felix
Felix

Reputation: 89566

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

Upvotes: -7

Related Questions