javaandroidandroid-activityactivity-lifecycleonrestoreinstancestate

Really how onRestoreInstanceState() works?


I need your help. I'm making a application and I use the methods onSaveInstanceState() and onRestoreInstanceState(), but second method doesn't work.

I can see how the program accesses to onSaveinstancestate() when the home button is pushed, but when I return to the application the code doesn't call onRestoreInstanceState() or onCreate().

As a result, the application start from scratch. I don't know the reason... can you help me?

This is my code:

public class MainActivity extends ActionBarActivity {

MyView myView;

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myView = new MyView(this);
        setContentView(myView);

    if (savedInstanceState != null) {
        myView .SetScore(savedInstanceState.getInt("Id"));
        myView .SetNivel(savedInstanceState.getInt("Valor"));  
    }
} 

.....

 @Override
    protected void onRestart(){
        super.onRestart();
        myView = new MyView(this);
        setContentView(myView );
    }

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
    super.onRestoreInstanceState(savedInstanceState);
    if (savedInstanceState != null) {
        myView.SetScore(savedInstanceState.getInt("Id"));
        myView.SetNivel(savedInstanceState.getInt("Valor"));
   }
}

@Override
protected void onSaveInstanceState(Bundle savedInstanceState){
    savedInstanceState.putInt("Score",myView.GetId());
    savedInstanceState.putInt("Nivel",muView.GetValor());
    super.onSaveInstanceState(savedInstanceState);
}
}

Solution

  • As the system begins to stop your activity, it calls onSaveInstanceState() so you can specify additional state data you'd like to save in case the Activity instance must be recreated. If the activity is destroyed and the same instance must be recreated, the system passes the state data defined to both the onCreate() method and the onRestoreInstanceState() method.

    You can check this https://developer.android.com/training/basics/activity-lifecycle/recreating.html

    You can see what happens with a Toast inside your method.

    And check this https://stackoverflow.com/a/4967491/3653989