title: Android Instrumentation Testing - UI Thread Issues
body: <p>I am trying to write an Instrumentation Test for my Android app.</p>
  <p>I'm running into some weird threading issues and I can't seem to find a solution.</p>
  <p><strong>My Original Test:</strong></p>
  <pre><code>@RunWith(AndroidJUnit4.class)
  public class WorkOrderDetailsTest {
  
      @Rule
      public ActivityTestRule&lt;WorkOrderDetails&gt; activityRule = new ActivityTestRule&lt;&gt;(WorkOrderDetails.class);
  
      @Test
      public void loadWorkOrder_displaysCorrectly() throws Exception {
          final WorkOrderDetails activity = activityRule.getActivity();
  
          WorkOrder workOrder = new WorkOrder();
          activity.updateDetails(workOrder);
  
          //Verify customer info is displayed
          onView(withId(R.id.customer_name))
                  .check(matches(withText(&quot;John Smith&quot;)));
      }
  }
  </code></pre>
  <p>This resulted in an</p>
  <blockquote>
  <p>android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.</p>
  <p>...</p>
  <p>com.kwtree.kwtree.workorder.WorkOrderDetails.updateDetails(WorkOrderDetails.java:155)</p>
  </blockquote>
  <p>The only thing the <code>updateDetails()</code> method does is some <code>setText()</code> calls.</p>
  <p>After researching a bit, it seemed like adding a <code>UiThreadTestRule</code> and <code>android.support.test.annotation.UiThreadTest</code> annotation to my test would fix the problem.</p>
  <p><strong>@UiThreadTest:</strong></p>
  <pre><code>@RunWith(AndroidJUnit4.class)
  public class WorkOrderDetailsTest {
  
      //Note: This is new
      @Rule
      public UiThreadTestRule uiThreadTestRule = new UiThreadTestRule();
  
      @Rule
      public ActivityTestRule&lt;WorkOrderDetails&gt; activityRule = new ActivityTestRule&lt;&gt;(WorkOrderDetails.class);
  
      @Test
      @UiThreadTest //Note: This is new
      public void loadWorkOrder_displaysCorrectly() throws Exception {
          final WorkOrderDetails activity = activityRule.getActivity();
  
          WorkOrder workOrder = new WorkOrder();
          activity.updateDetails(workOrder);
  
          //Verify customer info is displayed
          onView(withId(R.id.customer_name))
                  .check(matches(withText(&quot;John Smith&quot;)));
      }
  }
  </code></pre>
  <blockquote>
  <p>java.lang.IllegalStateException: Method cannot be called on the main application thread (on: main)</p>
  </blockquote>
  <p><em>(Note: All of the methods in this stack trace are not my code)</em></p>
  <p>It seems to be giving me mixed results... If it needs to be run on the original thread that created the views but can't run on the main thread, what thread should it be run on?</p>
  <p>I'd really appreciate any help or suggestions!</p>