Question

I've written a simple Activity that contains a ListView and a TextView. Upon selection of a ListView item, the TextView reflects the item text. I've specifically not added code for handling rotation changes. When I run the app, I get what's expected:

  • Clicked item is shown in TextView
  • Post rotation, default value of TextView is shown

However, after running my Test (extending ActivityInstrumentationTestCase2), this is what happens:

  • Value of clicked item is correctly recorded in my Test
  • Post rotation, the Test gets the same old value of TextView (even though I can see that the text has changed on my device!)

Here's my Test:

@Override
protected void setUp() throws Exception {
    super.setUp();
    mActivity=(MainActivity) getActivity();
    lv=(ListView) mActivity.findViewById(com.example.samplee.R.id.lv1);
    }

public void testDestroy() {
    mActivity.runOnUiThread(new Runnable() {

        @Override
        public void run() {
            lv.requestFocus();
            lv.setSelection(0);
        }
    });
    this.sendKeys(KeyEvent.KEYCODE_DPAD_DOWN);
    this.sendKeys(KeyEvent.KEYCODE_DPAD_DOWN);
    //select 2nd item in ListView
    this.sendKeys(KeyEvent.KEYCODE_DPAD_CENTER);
    TextView tv=(TextView)mActivity.findViewById(com.example.samplee.R.id.textView1);
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    String origValue=(String) tv.getText();
    mActivity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    try {
        Thread.sleep(1000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    tv=(TextView)mActivity.findViewById(com.example.samplee.R.id.textView1);
    String newValue=(String) tv.getText();  //gets same value as origValue!
    assertEquals(origValue,newValue);  //always succeds;
}

On some SO posts, I read about using getInstrumentation().waitForIdleSync() in place of my Thread.sleep() code. That too, didn't work.

I also tried Robotium. No change! Any pointers as to how to go about solving this?

Was it helpful?

Solution

After rotation you get a new Activity. Try replacing mActivity.findViewById(...) with solo.getCurrentActivity().findViewById(...).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top