DEMO 02

Save and Restore the Stopwatch

Run the clock. Rotate the phone. With the fix switched off it resets to zero; switch the fix on and the same rotation keeps the value.

What to do

Start the clock, let it reach about ten seconds, then hit Rotate the device with the switch off. Watch the number. Then switch it on and do exactly the same thing again.

Then askWhere exactly does the value get written down?

The Bundle panel on the right answers it — it shows the real key/value pairs, filled in at the moment the activity is taken down.

9:41portrait
STOPWATCH
00:00.0
What gets written down before the activity dies
Lifecycle during rotation
  1. Rotate the device to see the sequence.
The fix
Force a configuration change
The clock
Ready Start the clock and rotate the device with the fix off. Keep the number in your head — you are about to lose it.

The code that decides

Seven lines. The only difference between a stopwatch that survives rotation and one that does not.

Point atthe two matching key names.

Without it

the value dies with the activity
StopwatchActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_stopwatch);
    // nothing is read back — a fresh activity starts from zero
    seconds = 0;
}

With it

the value outlives the activity object
StopwatchActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_stopwatch);
    if (savedInstanceState != null) {          // arriving back from a rotation
        seconds = savedInstanceState.getInt("seconds");
        running = savedInstanceState.getBoolean("running");
    }
}

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("seconds", seconds);          // write it down before you die
    outState.putBoolean("running", running);
}
A phone displaying a stopwatch stopped at 00:00.00

Photo Image Hunter · Pexels #21792124 · the number the user sees after a rotation that nobody handled.

A static field survives rotation — and that is exactly the problem.

It also survives the user leaving the app, coming back tomorrow, and opening a second copy of the activity. You have created state that belongs to the process but is being used as if it belonged to the screen — the classic source of “why is my app showing yesterday's data?”.

onSaveInstanceState() has the right lifetime: it lives exactly as long as the task the user is looking at, and dies when they genuinely finish the activity.

One rule to remember: keep it small. The Bundle is passed through the system, so it is limited to roughly half a megabyte and it can only carry primitives and Parcelable values. Store the minimum needed to rebuild the screen — a number, a flag, an id — never a bitmap or a list of objects.