Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Junit test fails with " Only the original thread that created a view hierarchy can touch its views."

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

like image 834
surya Avatar asked Nov 05 '11 01:11

surya


2 Answers

@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

like image 71
Lukas Hanacek Avatar answered Nov 03 '22 13:11

Lukas Hanacek


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
            }
        });
like image 32
Lalit Poptani Avatar answered Nov 03 '22 15:11

Lalit Poptani