Search code examples
javaandroidrobotium

Android Robotium Testing, Runtime Exception This method can not be called from the main application thread


So I am testing my android app using Robotium and when I go to click on the item in my list it by solo.clickInList(0,1); using gives me

java.lang.RuntimeException: This method can not be called from the main application thread
at android.app.Instrumentation.validateNotAppThread(Instrumentation.java:1787)
at android.app.Instrumentation.runOnMainSync(Instrumentation.java:348)
at com.robotium.solo.Scroller.scrollListToLine(Scroller.java:326)
at com.robotium.solo.Scroller.scrollList(Scroller.java:276)
at com.robotium.solo.Scroller.scroll(Scroller.java:195)
at com.robotium.solo.Scroller.scroll(Scroller.java:156)
at com.robotium.solo.Scroller.scrollDown(Scroller.java:169)
at com.robotium.solo.Waiter.waitForView(Waiter.java:154)
at com.robotium.solo.Waiter.waitForAndGetView(Waiter.java:521)
at com.robotium.solo.Clicker.clickInList(Clicker.java:516)
at com.robotium.solo.Solo.clickInList(Solo.java:1244)
at com.teamname.tutortrader.AvailableSessionsActivityTest.testViewOneSession(AvailableSessionsActivityTest.java:119)
at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:214)
at android.test.InstrumentationTestCase.access$000(InstrumentationTestCase.java:36)
at android.test.InstrumentationTestCase$2.run(InstrumentationTestCase.java:189)
at android.app.Instrumentation$SyncRunnable.run(Instrumentation.java:1855)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

I am using the @UiThreadTest on top of my function.


Solution

  • As I found here it looks like a bug in robotium. https://stackoverflow.com/a/20200643/6150020. You can probably do the same thing by yourself without robotium.

    public void onListViewItemClick(){ Activity activity = getActivity(); final ListView listView = (ListView)activity.findViewById(android.R.id.list); getInstrumentation().runOnMainSync(new Runnable() { @Override public void run() { listView.performItemClick(listView.getAdapter().getView(0, null, null), 0, listView.getItemIdAtPosition(0)); } }); }