onCreate param: 'savedInstance' is allways null

197 views Asked by At

I'm learning basics of Android and I'm trying to save and retriever user preferences. I am using a physical device (Galaxy S4) to test the app. First I ensure the app calls the method 'onSaveInstanceState'

@Override
 public void onSaveInstanceState(Bundle savedInstanceState) {
    savedInstanceState.putInt(MyPreferences.COLOR_KEY, MyPreferences.BG_COLOR);        
    super.onSaveInstanceState(savedInstanceState);
    Log.i("i", "In onSaveInstanceState, COLOR_KEY value saved.");
}

(BG_COLOR is an int with a default value of 0).

Ones 'onSaveInstanceState' has been called, I force the app to shut down by 'CLEAR RAM' under RAM manager.

When i restart my app and onCreate is called, its parameter 'savedInstanceState' is allways null, and the Toast pop's up: "savedInstance was null".

@Override
protected void onCreate(Bundle savedInstanceState) {
    if(savedInstanceState != null){
        MyPreferences.BG_COLOR = (int) savedInstanceState.getInt(MyPreferences.COLOR_KEY);
        Toast.makeText(MainActivity.this,"savedInstance was NOT null", Toast.LENGTH_LONG).show();
    }
    else {
        Toast.makeText(MainActivity.this,"savedInstance was null", Toast.LENGTH_LONG).show();
    }
    setContentView(R.layout.activity_main);
    super.onCreate(savedInstanceState);
}

I wonder, have I totally misunderstood how the instance states are stored or is there some other error in my code?

2

There are 2 answers

0
eduyayo On BEST ANSWER

Saved instance is not for restoring the instance after the application got killed or resumed after process ended somehow. It is to restore the object instance after some configuration change that will destroy and recreate the object inmediatelly such as phone being tilted or something.

After a process restart you can only have a null value for it.

You better use Shared Preferences in this case to keep track of your values.

1
Blackbelt On

When i restart my app and onCreate is called, its parameter 'savedInstanceState' is allways null, and the Toast pop's up: "savedInstance was null".

That's the expected behaviour. savedInstanceState is persisted only across configurations change, like the screen orientation. In your case your probably want to use the shared preferences to store your status