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

2

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

Twiddle answered 5/11, 2011 at 1:13 Comment(1)
I guess it's because your testcases try to dismiss the lock screen #4545579Sporocyst
P
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

Pounce answered 14/11, 2011 at 10:19 Comment(0)
B
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
            }
        });
Battik answered 14/11, 2011 at 10:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.