savedInstanceState is always null

Android

Android Problem Overview


This is my savedInstaceState code:

@Override
public void onSaveInstanceState(Bundle savedInstanceState) 
{
	savedInstanceState.putStringArrayList("todo_arraylist", Altodo);
	Log.v("bundle", "Saved");
	super.onSaveInstanceState(savedInstanceState);
}


public void onCreate(Bundle savedInstanceState) 
{
	super.onCreate(savedInstanceState);

	if (savedInstanceState != null) 
	{
		Altodo = savedInstanceState.getStringArrayList("todo_arraylist");
		Log.v("bundle", "Restored");
	}
	else
	{
		Log.v("bundle", "null");
	}

	setContentView(R.layout.main);
}

The logs always show the "bundle save" tag.

But in onCreate method, SavedInstanceState is always null.

Android Solutions


Solution 1 - Android

I observed the exact same symptoms (reported as issue 133394) in a project with two Activities A and B that extend ActionBarActivity. Activity A is the main activity, and I always receive null for savedInstanceState in onCreate of its list fragment when returning from a detail view activity B. After many hours, this problem exposed itself to me as a navigation issue in disguise.

The following may be relevant to my setup and come from other answers on this page:

  • Given this answer, I made sure that fragment and activity each have unique IDs set.
  • There is no override of onSaveInstanceState without super call.
  • Activity A is specified as acitivy B's parent in AndroidManifest.xml, using both the android:parentActivityName attribute and the corresponding meta-data tag for earlier versions of Android (see "Providing Up Navigation").

Already without any corresponding creation code such as getActionBar() .setHomeButtonEnabled(true), activity B has a functioning back button (<) in its action bar. When this button is tapped, activity A reappears but with (a) all previous instance state lost, (b) onCreate always called, and (c) savedInstanceState always null.

Interestingly, when I tap the back button provided at the bottom edge of the emulator display (an open triangle that points to the left), activity A reappears just as it was left (i.e. its instance state fully retained) without invoking onCreate. So maybe something is wrong with navigation?

After more reading, I implemented my own navigation instructions to run in response to a tap on the back-button in activity B:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == android.R.id.home)
        NavUtils.navigateUpFromSameTask(this);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

Nothing related to restoring instance state of activity A changed. NavUtils also provide a method getParentActivityIntent(Activity) and navigateUpTo(Activity, Intent) that allow us to modify the navigation intent to explicitly instruct that activity A is not started fresh (and thus without saved instance state provided) by setting the FLAG_ACTIVITY_CLEAR_TOP flag:

> If set, and the activity being launched is already running in the > current task, then instead of launching a new instance of that > activity, all of the other activities on top of it will be closed and > this Intent will be delivered to the (now on top) old activity as a > new Intent.

In my hands, this solves problem of lost instance state and could look like:

public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId()== android.R.id.home) {
        Intent intent = NavUtils.getParentActivityIntent(this);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        NavUtils.navigateUpTo(this, intent);
        return true;
    }
    return super.onOptionsItemSelected(item);
}

Note that this may not be the complete solution in other cases where a user can switch directly to activity B from within a different task (see here). Also, a possibly identical solution in behavior that does not make use of NavUtils is to simply call finish():

public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId()== android.R.id.home) {
        finish();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

Both solutions work in my hands. I am only speculating that the original issue is a slightly incorrect default implementation of the back-button, and it may be related to that implementation invoking some kind of navigateUp that misses FLAG_ACTIVITY_CLEAR_TOP.

Solution 2 - Android

Did you check if you have an Id set for that view ( if a view it is/has...). onSaveInstanceState() is not called otherwise.

Check this link.

Solution 3 - Android

The state saved in this manner is not persisted. If the whole application is killed as you are doing during debugging, the bundle will always be null in onCreate.

This IMO is yet another example of awful Android documentation. It's also why most apps in the marketplace don't implement saving state properly (at all).

Solution 4 - Android

in Manifest add this line for activities

android:launchMode="singleTop"

for example:

<activity
        android:name=".ActivityUniversity"
        android:label="@string/university"
        android:launchMode="singleTop"
        android:parentActivityName="com.alkhorazmiy.dtm.ActivityChart">
        <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value="com.alkhorazmiy.dtm.ActivityChart" />
    </activity>

Solution 5 - Android

How do you test it?

Imo the best way to test it is using the "Don't keep activities"-flag in Settings > Developer Options. If you don't have Developer Options in Settings, see Enabling On-device Developer Options.

  1. Open your activity
  2. Long-press home
  3. Go to another application
  4. Long-press home
  5. Go back to your application

Solution 6 - Android

Shouldn't super.onSaveInstanceState(savedInstanceState); be the first line in your override?

Edit: War_Hero points out in the comments that the documentation on that topic indicates that no, it shouldn't be the first line.

Solution 7 - Android

Check your activity in AndroidManifest.xml and remove android:noHistory property if is true.

<activity
    // ....
    android:noHistory="false" />

Solution 8 - Android

To debug, consider implementing onRestoreInstanceState and placing a call to Log.d in this method. Then, in the emulator, hit ctrl-F11 or whatever to rotate the phone. Your call to Log.d should be hit.

Solution 9 - Android

Implement a method of onRestoreInstanceState and put below code there

Altodo = savedInstanceState.getStringArrayList("todo_arraylist");

Solution 10 - Android

I found that when I override onSaveInstanceState() and actually save some data in the Bundle, instance state is restored. Otherwise it's not.

Solution 11 - Android

Ive managed same way arround. Instead of handling savedInstanceState Bundle on the onCreateView method, ive handled it on onCreate method and setting the passed value to a globar variable then acessing this variable on the onCreateView method. Hope it helps.

Solution 12 - Android

https://developer.android.com/guide/topics/manifest/activity-element#lmode

From this you can see 'Similarly, if you navigate up to an activity on the current stack, the behavior is determined by the parent activity's launch mode.' Maybe you are in the 'standard' mode.

Solution 13 - Android

I was able to solve it with:

@Override public boolean onSupportNavigateUp()
{
    onBackPressed();
    return true;
}

still had parent set in the manifest. So when you press the up navigation button, now it acts like the back button.

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
QuestionmedView Question on Stackoverflow
Solution 1 - Androids.bandaraView Answer on Stackoverflow
Solution 2 - AndroidPHFView Answer on Stackoverflow
Solution 3 - AndroidmxclView Answer on Stackoverflow
Solution 4 - AndroidAl KhorazmiyView Answer on Stackoverflow
Solution 5 - AndroidmibollmaView Answer on Stackoverflow
Solution 6 - AndroidJonathan AllardView Answer on Stackoverflow
Solution 7 - AndroidAmirHossein ManianView Answer on Stackoverflow
Solution 8 - AndroidJALView Answer on Stackoverflow
Solution 9 - AndroidDharmendraView Answer on Stackoverflow
Solution 10 - AndroidAron LorinczView Answer on Stackoverflow
Solution 11 - AndroidHorácio ComéView Answer on Stackoverflow
Solution 12 - AndroidIn New OatView Answer on Stackoverflow
Solution 13 - AndroidChuckView Answer on Stackoverflow