Search code examples
androidandroid-handleronsaveinstancestate

savedInstanceState gives me a wrong value


I have a stopwatch app and it has just one activity. Three buttons start, stop, reset and a textview to show the timer. Here is my code :

public class StopwatchActivity extends AppCompatActivity {

private int mNumberOfSeconds = 0;
private boolean mRunning = false;
private Handler handler = new Handler();
private Runnable runnable;
private TextView timeview;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_stopwatch);

    if (savedInstanceState != null){
        mNumberOfSeconds = savedInstanceState.getInt("number_of_second");
        mRunning = savedInstanceState.getBoolean("is_running");
        Log.e("after orient mSecond :" , String.valueOf(mNumberOfSeconds));
        Log.e("after orient mRunning :" , String.valueOf(mRunning));
        runner();
    }

}

public void onClickStart(View view){
    handler.removeCallbacks(runnable);
    mRunning = true;
    runner();
}

public void onClickStop(View view){
    mRunning = false;
    handler.removeCallbacks(runnable); 
}

public void onClickReset(View view){
    mRunning = false;
    //mNumberOfSeconds = 0;
    //timeview.setText("0:00:00");


}

public void runner(){
    timeview = (TextView) findViewById(R.id.time_view);
    runnable = new Runnable() {
        @Override
        public void run() {
            int hours = mNumberOfSeconds/3600;
            int minutes = (mNumberOfSeconds%3600)/60;
            int second = mNumberOfSeconds%60;
            String time = String.format("%d:%02d:%02d" , hours , minutes , second );
            timeview.setText(time);
            if (mRunning){
                mNumberOfSeconds++;
            }
            handler.postDelayed(this , 1000);
        }
    };
    handler.post(runnable);

}

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putInt("number_of_seconds" , mNumberOfSeconds);
    outState.putBoolean("is_running" , mRunning);
    Log.e("befor rotation second:" , String.valueOf(mNumberOfSeconds));
    Log.e("befor rotaion mrunning" , String.valueOf(mRunning));

}

I want to save some of my variables in onSaveInstanceState to get use of them again after orientation changing. As you can see in the code the log message show the value of mNumberOfSeconds and mRunning before and after orientation changes. And after orientation changes mNumberOfSeconds will give me 0 instead of the value I saved. But mRunning gives me the right value. Can anyone give me any solution?


Solution

  • You can avoid this in the future by using tags in the put() and get() calls:

    private static final String KEY_NUM_SECS = "NUM_SECS";
    

    then use it like this:

    mNumberOfSeconds = savedInstanceState.getInt(KEY_NUM_SECS);
    

    and:

    outState.putInt(KEY_NUM_SECS, mNumberOfSeconds);