views:

55

answers:

1

I'm trying to understand the Activity Testing tutorial on the Android site. One of the tests sets a spinner in the SpinnerActivity example, forces a pause, then resets the spinner, forces a resume, and then verifies that the application properly restored the state. I pasted the relevant code at the bottom of this question for reference.

I'm very confused why the person writing the test thinks that the spinner could have been corrupted between the OnPause() and OnResume(). Is this because the spinner could have been reused in some subsequent activity and thus lost its state? That's the only reasonable explanation I can think of.

I'm concerned about preserving my application's activities non-widget members such as Strings, ints, etc. These are initialized during OnCreate and won't be changed by the user. As a result, I don't see any reason to save them off during OnPause, because even if the OS directly terminates the activity after a pause, the OnCreate() will re-initialize these members.

Is it safe then to assume that these non-widget members will not be harmed when pausing (assuming that the application eventually resumes?)

 public void testStatePause() {
    Instrumentation mInstr = this.getInstrumentation();
    mActivity.setSpinnerPosition(TEST_STATE_PAUSE_POSITION);
    mActivity.setSpinnerSelection(TEST_STATE_PAUSE_SELECTION);
    mInstr.callActivityOnPause(mActivity);          
    mActivity.setSpinnerPosition(0);
    mActivity.setSpinnerSelection("");
    mInstr.callActivityOnResume(mActivity);
    int currentPosition = mActivity.getSpinnerPosition();
    String currentSelection = mActivity.getSpinnerSelection();
    assertEquals(TEST_STATE_PAUSE_POSITION,currentPosition);
    assertEquals(TEST_STATE_PAUSE_SELECTION,currentSelection);
 }          
+1  A: 

The likely reason is because your app can be killed when in a paused state. Take this example:

  1. onCreate - initialize to 5
  2. user selects 3
  3. user leaves activity, activity paused
  4. Android deletes activity b/c it needs resources
  5. user returns to activity
  6. onCreate is called - initialized to 5
  7. onResume is called - Sees that there is saved data, results value to 3
Mayra
I think my confusion stems from the fact that I'd expect to step 7's behavior covered in step 6 inside OnCreate(). If the activity were terminated, OnResume() would never be called without a prior OnCreate() call, right? I don't see the value in incurring this typically unnecessary context restoring overhead in OnResume(), when it could be handled only when needed in OnCreate(). Am I misunderstanding something?
glenviewjeff
You are right, I don't think there is any reason you couldn't handle that in onCreate. You do need to save it in onPause though.
Mayra