due at midnight on +125
Your task for this milestone is to have an Android activity that can successfully save and restore its state across the destruction of that activity. The simplest way to trigger the save and restore is by changing the device’s orientation (Ctrl-F12 does that on my emulator). To save, you will override onSaveInstanceState
and call the outState.put…
methods. For example:
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(ID_CURRENT_SCORE, currentScore);
}
where you declare ID_CURRENT_SCORE
as a string constant within your class, so you are consistent about using the same field name when you restore (Don’t Repeat Yourself):
private static final String ID_CURRENT_SCORE = "currentScore";
To restore, the onCreate
method you already have is given a savedInstanceState
. It will be null
if there is no current state, so you include a bit of logic like this:
if(savedInstanceState == null) { // We start fresh
currentScore = 0;
}
else { // We restore existing state
currentScore = savedInstanceState.getInt(ID_CURRENT_SCORE);
}
You can do this with the memory game, or if you prefer, try a different app that I’ll describe below. (Or do both, if you want the practice!)
I started to handle save/restore in class on Feb 25, but the state variables needed just a bit of restructuring. You can fill in the rest. As a clue, here are the state variables I ended up with in my final solution:
private int cardValues[];
private ArrayList<Integer> faceUpIndices = new ArrayList<Integer>();
private ArrayList<Integer> removedIndices = new ArrayList<Integer>();
They track the values on the front sides of the cards, which cards are face-up, and which cards have been removed from the game.
More detail in class on March 2 .