18

I am very new to Android and am writing some basic Android tests using Robotium and this fails with exception as

"android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views."

Below is the basic testcase decription:-

testcase:-

public void testSearch() {
                        Activity a = getActivity();
            SearchItemActivity search = new SearchItemActivity(solo);
            search.searchText("ipod", a);   

    }

 SearchItemActivity.searchText(String) is defined as

    public void searchText(final String search, Activity act) {
                Button v = (Button) act
                .findViewById(com.test.mobile.R.id.text_search_field);
                ((Button) v).setText("");
                ((Button) v).setText(search);
                solo.sendKey(Solo.ENTER);
                solo.waitForActivity("FoundItemdDetailActivity");
                solo.assertCurrentActivity("Expected FoundItemDetail activity","FoundItemdDetailActivity");
    }

Any suggestions how I can modify my code will be appreciatated

surya
  • 181
  • 1
  • 5
  • I guess it's because your testcases try to dismiss the lock screen http://stackoverflow.com/questions/4545079/lock-the-android-device-programatically/10535284#10535284 – Hieu Rocker Jan 01 '14 at 15:15

2 Answers2

27
@UiThreadTest
public void yourMethod() {

The @UiThreadTest annotation tells Android to build this method so that it runs on the UI thread. This allows the method to change the state of the spinner widget in the application under test. This use of @UiThreadTest shows that, if necessary, you can run an entire method on the UI thread.

http://developer.android.com/tools/testing/activity_test.html

laplasz
  • 3,359
  • 1
  • 29
  • 40
Lukas Hanacek
  • 1,364
  • 14
  • 25
7

I guess you are trying to update the UI from a non-UI thread. So for that you need to put your code inside the runOnUiThread().

ActivityName.this.runOnUiThread(new Runnable() {

            public void run() {
                // your code to update the UI
            }
        });
Lalit Poptani
  • 67,150
  • 23
  • 161
  • 242