akohout
akohout

Reputation: 1811

How to save/restore fragment state when device screen turned off and on again

I have a fragment with an EditText in it, where users can enter a longer text. Now when users type something, turn the screen off for whatever reason, and then turn the screen on again the EditText is empty.

I thought that onSaveInstance should be the right place to save the state, and any of the create methods (that actually have the saveInstance parameter) should be enough to retrieve the previously saved state - but it's not working. onSaveInstance is called, but the create methods do not retrieve this object.

So the question: How can I save my fragment's state when screens turn off, and how can I restore this state when the screen is turned on again?

Edit: I have implemented blackbelt's approach, but it's still not working. (savedInstanceState is null)

@Override
public void onActivityCreated(final Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    if (savedInstanceState != null) {
        review.finalStatement = savedInstanceState.getString
                (BUNDLE_KEY_STATEMENT);
    }
}

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

    outState.putString(BUNDLE_KEY_STATEMENT, review.finalStatement);
}

Upvotes: 1

Views: 708

Answers (1)

Blackbelt
Blackbelt

Reputation: 157457

I have a fragment with an EditText in it, where users can enter a longer text. Now when users type something, turn the screen off for whatever reason, and then turn the screen on again the EditText is empty.

It is not the default behaviour. EditText states should be kept as it was.

I thought that onSaveInstance should be the right place to save the state, and any of the create methods (that actually have the saveInstance parameter) should be enough to retrieve the previously saved state - but it's not working. onSaveInstance is called, but the create methods do not retrieve this object.

It is. You should use the pair onSavedInstanceState/onActivityCreated and not onCreate

Upvotes: 1

Related Questions