Question

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);
 }          
Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top