Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onCreate(Bundle savedInstanceState) in always null

I know, this question is asked before on stackoverflow, but non of the answers worked for me.

Probably worth mentioning:

  • I use ActionBarSherlock with the support package.
  • Method onSaveInstanceState IS called when I press the home button. The method onCreate just always gives NULL for the Bundle savedInstanceState.
  • Method onRestoreInstanceState is never called at all. (I wouldn't mind if the onCreate worked ;)).
  • Also (it shouldn't matter) I tried putting super.onSaveInstanceState(outState) at the bottom of onSaveInstanceState. No luck either.

Here's the code. I hope someone had this problem and solved it.

public class MainActivity extends SherlockFragmentActivity {

    private static final String LOG_TAG = MainActivity.class.getSimpleName();

    private static String STATE_TO_STORE = "state_to_store";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        

        Log.d(LOG_TAG, "onCreate: savedInstanceState = " + (savedInstanceState == null ? "NULL" : "Not NULL"));

        // ... more code...
    }

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

        Log.d(LOG_TAG, "onRestoreInstanceState: savedInstanceState = " + (savedInstanceState == null ? "NULL" : "Not NULL"));
    }

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

        outState.putInt(STATE_TO_STORE, 5); // store some int

        Log.d(LOG_TAG, "onSaveInstanceState bundle: " + outState.toString());
    }

    // ... more code ...

}

The logging clearly states onSaveInstanceState is being called and onCreate gets savedInstanceState = NULL.

like image 523
Almer Avatar asked Mar 28 '13 16:03

Almer


2 Answers

Check that your manifest does not contain android:noHistory="true".

I spent hours looking for an answer and it was that simple.

like image 118
user2360033 Avatar answered Sep 18 '22 08:09

user2360033


In my case, the reason was that the specific activity did not have a theme declared in the manifest file.

To fix this, open AndroidManifest.xml, click Application, select the crashing activity in Application Nodes and add the theme in the Theme field of Attributes. In my case, it was

@style/Theme.AppCompat.Light.DarkActionBar

but you could copy the theme from one of your other activities.

P.S.: I know this is an answer to an old question, but I've stumbled upon it while searching for a fix and didn't find a working solution so this might help others.

like image 43
Vlad Schnakovszki Avatar answered Sep 21 '22 08:09

Vlad Schnakovszki