Remembering the Current Position

If you change the screen orientation while Sudoku is running, you'll notice that it forgets where its cursor is. That's because we use a custom PuzzleView view. Normal Android views save their view state automatically, but since we made our own, we don't get that for free.

unlike persistent state, instance state is not permanent. It lives in a Bundle class on Android's application stack. Instance state is intended to be used for small bits of information such as cursor positions.

Here's what we have to do to Implement It:

Download Sudokuv4/src/org/example/sudoku/PuzzleView.java

Line 1 import android.os.Bundle;

- import android.os.Parcelable;

- public class PuzzleView extends View {

5 private static final String SELX = "selX";

- private static final String SELY = "selY";

private static final String VIEW_STATE = "viewState";

- private static final int ID = 42;

10 public PuzzleView(Context context) {

15 ©Override protected Parcelable onSaveInstanceState() {

- Parcelable p = super.onSaveInstanceState(); Log.d(TAG, "onSaveInstanceState");

Bundle bundle = new Bundle(); 20 bundle.putInt(SELX, selX);

- bundle.putInt(SELY, selY); bundle.putParcelable(VIEW_STATE, p);

25 ©Override

- protected void onRestoreInstanceState(Parcelable state) {

Log.d(TAG, "onRestoreInstanceState");

- select(bundle.getInt(SELX), bundle.getInt(SELY));

30 super.onRestoreInstanceState(bundle.getParcelable(VIEW_STATE));

On line 5, we define some constants for keys to save and restore the cursor position. We need to save both our own x and y positions, plus any state needed by the underlying View class.

As part of Activity.onSaveInstanceState() processing, Android will walk down the view hierarchy and call View.onSaveInstanceState() on every view it finds that has an ID. The same thing happens for onRestoreIn-stanceState(). Normally, this ID would come from XML, but since PuzzleView was created in code, we need to set it ourselves. We make up an arbitrary number on line 8 (any value will do as long as it's positive) and then use the setId() method to assign it on line 12.

Report erratum

The onSaveInstanceState() method is defined on line 16. We call the superclass to get its state, and then we save ours and theirs in a Bundle. Failing to call the superclass will result in a runtime error.

Later, onRestoreInstanceState() (line 26) will be called to tease out the information we saved. We get our own x and y positions from the Bundle, and then we call the superclass to let it get whatever it needs. After making these changes, the cursor will be remembered by PuzzleView, just like any other Android view.

Next let's look at keeping data in plain old files.

0 0

Post a comment