Save the Shard’s state?

Asked

Viewed 357 times

1

In a simple app I have Fragments and need to save their state,

so that when the user returns from one fragment to the other,

the typed text, chosen number, checked box, etc... suggestions ?

1 answer

1

  1. In the fragment, saves the state overriding onSaveInstanceState() and keeps in onActivityCreated():
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    ...
    if (savedInstanceState != null) {
        //Restore the fragment's state here
    }
}

...
@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    //Save the fragment's state here
}
  1. In the activity, you must save the instance of the fragment in the onSaveInstanceState() and keeps it in onCreate().
public void onCreate(Bundle savedInstanceState) {
    ...
    if (savedInstanceState != null) {
        //Restore the fragment's instance
        mContent = getSupportFragmentManager().getFragment(savedInstanceState, "mContent");
        ...
    }
    ...
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    //Save the fragment's instance
    getSupportFragmentManager().putFragment(outState, "mContent", mContent);
}

I hope this helps.

I wanted to comment, because the answer was already given in the English SO, but as I could not, I wrote here and translated. I hope this helps.

https://stackoverflow.com/questions/15313598/once-for-all-how-to-correctly-save-instance-state-of-fragments-in-back-stack

The code isn’t going to code, if anyone knows by, I’d appreciate it!!

  • Not quite, but thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.