0

Could the savedInstanceState parameter passed to Activity.onCreate have been saved by a different version of the app? I can't find any reference to this in the documentation.

This could be theoretically possible if the activity was backgrounded, then killed due to low memory, then a new version of the app was installed, and then the user navigated back to the activity using the recents list.

In the example code below, could onCreate throw an ArrayIndexOutOfBoundsException or set a surprising state if the enum has been changed between versions, or is the code safe?

public class ExampleActivity extends Activity {
  private enum State {
    SOMETHING,
    SOMETHING_ELSE,
    ANOTHER_THING,
    ET_CETERA,
  }
  private State state;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (savedInstanceState != null) {
      state = State.values()[savedInstanceState.getInt("state")];
    } else {
      state = State.ANOTHER_THING;
    }
  }

  @Override
  protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("state", state.ordinal());
  }

  // ...
}
Karu
  • 4,512
  • 4
  • 30
  • 31

2 Answers2

4

No. SavedInstanceState is not used to persist data across new instances of the same app. It is used to temporarily store data during the current app's 'session'.

In other words, the values you supply to the savedInstanceState bundle are stored when your activity is destroyed, for example, when you rotate the screen. These values are then retrieved when the activity is recreated.

When you quit the app entirely, or install a new version, these values are lost.

Tim Malseed
  • 6,003
  • 6
  • 48
  • 66
  • I realised my two questions were contradictory - I fixed it up to match the question title, but I believe your answer should now say "No" :) – Karu Nov 30 '15 at 00:57
1

Theoretically always. Before you upgrade (change) application. It deactivated and later starts over. Now Android Studio added functionality "Instant Run", and in this case may possibly occur such an exception. More I do not have any ideas. It seems to me that such a check is not necessary right now. For all the time my development I've never encountered similar cases and have not heard about such an.

user2413972
  • 1,355
  • 2
  • 9
  • 25