I found many answers to this problem, but none of them seem to work. This is the code in the Activity
:
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putString(CUR_TASK, curTask);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
as you see, super.onSaveInstanceState(savedInstanceState)
is at the end, so it should work. My layout does have an id
, so that should be OK too:
<android.support.v4.widget.DrawerLayout
android:id="@+id/drawer_layout"
still, when I call startActivity
to go to another Activity
and return back (using the ActionBar
), the savedInstanceState
bundle in onCreate
is null.
From the documentation on activity lifecycle:
Note: Because onSaveInstanceState() is not guaranteed to be called, you should use it only to record the transient state of the activity (the state of the UI)—you should never use it to store persistent data. Instead, you should use onPause() to store persistent data (such as data that should be saved to a database) when the user leaves the activity.
The method onSaveInstanceState
is not used for your purpose, it's used in a case like screen rotation to save UI state.
You have to switch your logic passing the values through the intent when the first Activity
launches the second one and passing the values back again using onActivityResult()
.
In addition, I recommend you to restore your state not in onCreate()
but in onRestoreInstanceState(Bundle savedInstanceState)
in which you are ALWAYS sure that your savedInstanceState
Bundle
isn't null.