Merge "Update view when a contact is removed."
diff --git a/res/layout/call_log_list_item_layout.xml b/res/layout/call_log_list_item_layout.xml
index 344413c..4fbe426 100644
--- a/res/layout/call_log_list_item_layout.xml
+++ b/res/layout/call_log_list_item_layout.xml
@@ -20,6 +20,7 @@
         android:layout_height="?attr/call_log_list_contact_photo_size"
         android:layout_toRightOf="@id/contact_photo"
         android:layout_toLeftOf="@id/divider"
+        android:layout_alignWithParentIfMissing="true"
         android:layout_marginLeft="?attr/call_log_inner_margin"
     >
         <include layout="@layout/call_log_phone_call_details"/>
diff --git a/res/values/strings.xml b/res/values/strings.xml
index 54ed931..b90898d 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -1623,6 +1623,9 @@
     <!-- Initial display for position of current playback, do not translate. -->
     <string name="voicemail_initial_time">00:05</string>
 
+    <!-- Message to show when there is an error playing back the voicemail. -->
+    <string name="voicemail_playback_error">Could not play voicemail</string>
+
     <!-- The separator between the call type text and the date in the call log [CHAR LIMIT=3] -->
     <string name="call_log_type_date_separator">/</string>
 
diff --git a/src/com/android/contacts/CallDetailActivity.java b/src/com/android/contacts/CallDetailActivity.java
index 2bea2f3..14fec85 100644
--- a/src/com/android/contacts/CallDetailActivity.java
+++ b/src/com/android/contacts/CallDetailActivity.java
@@ -174,13 +174,7 @@
     public void onResume() {
         super.onResume();
         updateData(getCallLogEntryUris());
-        Uri voicemailUri = getIntent().getExtras().getParcelable(EXTRA_VOICEMAIL_URI);
-        optionallyHandleVoicemail(voicemailUri);
-        if (voicemailUri != null) {
-            mAsyncQueryHandler.startVoicemailStatusQuery(voicemailUri);
-        } else {
-            mStatusMessageView.setVisibility(View.GONE);
-        }
+        optionallyHandleVoicemail();
     }
 
     /**
@@ -189,18 +183,22 @@
      * If the Intent used to start this Activity contains the suitable extras, then start voicemail
      * playback.  If it doesn't, then hide the voicemail ui.
      */
-    private void optionallyHandleVoicemail(Uri voicemailUri) {
+    private void optionallyHandleVoicemail() {
+        Uri voicemailUri = getIntent().getParcelableExtra(EXTRA_VOICEMAIL_URI);
         FragmentManager manager = getFragmentManager();
         VoicemailPlaybackFragment fragment = (VoicemailPlaybackFragment) manager.findFragmentById(
                 R.id.voicemail_playback_fragment);
-        if (voicemailUri == null) {
-            // No voicemail uri: hide the voicemail fragment.
-            manager.beginTransaction().hide(fragment).commit();
-        } else {
-            // A voicemail: extra tells us if we should start playback or not.
-            boolean startPlayback = getIntent().getExtras().getBoolean(
+        if (voicemailUri != null) {
+            // Has voicemail uri: leave the fragment visible.  Optionally start the playback.
+            // Do a query to fetch the voicemail status messages.
+            boolean startPlayback = getIntent().getBooleanExtra(
                     EXTRA_VOICEMAIL_START_PLAYBACK, false);
             fragment.setVoicemailUri(voicemailUri, startPlayback);
+            mAsyncQueryHandler.startVoicemailStatusQuery(voicemailUri);
+        } else {
+            // No voicemail uri: hide the voicemail fragment and the status view.
+            manager.beginTransaction().hide(fragment).commit();
+            mStatusMessageView.setVisibility(View.GONE);
         }
     }
 
diff --git a/src/com/android/contacts/CallDetailActivityQueryHandler.java b/src/com/android/contacts/CallDetailActivityQueryHandler.java
index c1d87b2..df5b4f7 100644
--- a/src/com/android/contacts/CallDetailActivityQueryHandler.java
+++ b/src/com/android/contacts/CallDetailActivityQueryHandler.java
@@ -57,8 +57,8 @@
      * If the voicemail record does not have an audio yet then it fires the second query to get the
      * voicemail status of the associated source.
      */
-    public void startVoicemailStatusQuery(Uri voicemaiUri) {
-        startQuery(QUERY_VOICEMAIL_CONTENT_TOKEN, null, voicemaiUri, VOICEMAIL_CONTENT_PROJECTION,
+    public void startVoicemailStatusQuery(Uri voicemailUri) {
+        startQuery(QUERY_VOICEMAIL_CONTENT_TOKEN, null, voicemailUri, VOICEMAIL_CONTENT_PROJECTION,
                 null, null, null);
     }
 
@@ -67,11 +67,12 @@
         try {
             if (token == QUERY_VOICEMAIL_CONTENT_TOKEN) {
                 // Query voicemail status only if this voicemail record does not have audio.
-                if (cursor.moveToFirst() && hasNoAudio(cursor)) {
+                if (moveToFirst(cursor) && hasNoAudio(cursor)) {
                     startQuery(QUERY_VOICEMAIL_STATUS_TOKEN, null,
                             Status.buildSourceUri(getSourcePackage(cursor)),
                             VoicemailStatusHelperImpl.PROJECTION, null, null, null);
                 } else {
+                    // nothing to show in status
                     mCallDetailActivity.updateVoicemailStatusMessage(null);
                 }
             } else if (token == QUERY_VOICEMAIL_STATUS_TOKEN) {
@@ -84,6 +85,15 @@
         }
     }
 
+    /** Check that the cursor is non-null and can be moved to first. */
+    private boolean moveToFirst(Cursor cursor) {
+        if (cursor == null || !cursor.moveToFirst()) {
+            Log.e(TAG, "Cursor not valid, could not move to first");
+            return false;
+        }
+        return true;
+    }
+
     private boolean hasNoAudio(Cursor voicemailCursor) {
         return voicemailCursor.getInt(HAS_CONTENT_COLUMN_INDEX) == 0;
     }
diff --git a/src/com/android/contacts/calllog/CallLogListItemHelper.java b/src/com/android/contacts/calllog/CallLogListItemHelper.java
index 72d489d..d4f2291 100644
--- a/src/com/android/contacts/calllog/CallLogListItemHelper.java
+++ b/src/com/android/contacts/calllog/CallLogListItemHelper.java
@@ -55,10 +55,19 @@
             boolean useIcons, boolean isHighlighted) {
         mPhoneCallDetailsHelper.setPhoneCallDetails(views.phoneCallDetailsViews, details, useIcons,
                 isHighlighted);
-        views.callView.setVisibility(
-                mPhoneNumberHelper.canPlaceCallsTo(details.number)
-                        ? View.VISIBLE : View.INVISIBLE);
-        views.playView.setVisibility(
-                details.callTypes[0] == Calls.VOICEMAIL_TYPE ? View.VISIBLE : View.GONE);
+        boolean callVisible = mPhoneNumberHelper.canPlaceCallsTo(details.number);
+        boolean playVisible = details.callTypes[0] == Calls.VOICEMAIL_TYPE;
+
+        if (callVisible || playVisible) {
+            // At least one is visible. Keep the divider and the space for the call button.
+            views.callView.setVisibility(callVisible ? View.VISIBLE : View.INVISIBLE);
+            views.playView.setVisibility(playVisible ? View.VISIBLE : View.GONE);
+            views.dividerView.setVisibility(View.VISIBLE);
+        } else {
+            // Neither is visible, remove all of them entirely.
+            views.callView.setVisibility(View.GONE);
+            views.playView.setVisibility(View.GONE);
+            views.dividerView.setVisibility(View.GONE);
+        }
     }
 }
diff --git a/src/com/android/contacts/calllog/CallLogListItemViews.java b/src/com/android/contacts/calllog/CallLogListItemViews.java
index c34779d..b66d84e 100644
--- a/src/com/android/contacts/calllog/CallLogListItemViews.java
+++ b/src/com/android/contacts/calllog/CallLogListItemViews.java
@@ -34,6 +34,8 @@
     public final ImageView callView;
     /** The play action button used for voicemail. */
     public final ImageView playView;
+    /** The divider between callView and playView. */
+    public final View dividerView;
     /** The details of the phone call. */
     public final PhoneCallDetailsViews phoneCallDetailsViews;
     /** The item view for a stand-alone row, or null for other types of rows. */
@@ -44,11 +46,12 @@
     public final TextView listHeaderTextView;
 
     private CallLogListItemViews(QuickContactBadge photoView, ImageView callView,
-            ImageView playView, PhoneCallDetailsViews phoneCallDetailsViews, View listItemView,
-            View listHeaderView, TextView listHeaderTextView) {
+            ImageView playView, View dividerView, PhoneCallDetailsViews phoneCallDetailsViews,
+            View listItemView, View listHeaderView, TextView listHeaderTextView) {
         this.photoView = photoView;
         this.callView = callView;
         this.playView = playView;
+        this.dividerView = dividerView;
         this.phoneCallDetailsViews = phoneCallDetailsViews;
         this.listItemView = listItemView;
         this.listHeaderView = listHeaderView;
@@ -59,6 +62,7 @@
         return new CallLogListItemViews((QuickContactBadge) view.findViewById(R.id.contact_photo),
                 (ImageView) view.findViewById(R.id.call_icon),
                 (ImageView) view.findViewById(R.id.play_icon),
+                view.findViewById(R.id.divider),
                 PhoneCallDetailsViews.fromView(view),
                 view.findViewById(R.id.call_log_item),
                 view.findViewById(R.id.call_log_header),
@@ -66,9 +70,11 @@
     }
 
     public static CallLogListItemViews createForTest(QuickContactBadge photoView,
-            ImageView callView, ImageView playView, PhoneCallDetailsViews phoneCallDetailsViews,
-            View standAloneItemView, View standAloneHeaderView, TextView standAloneHeaderTextView) {
-        return new CallLogListItemViews(photoView, callView, playView, phoneCallDetailsViews,
-                standAloneItemView, standAloneHeaderView, standAloneHeaderTextView);
+            ImageView callView, ImageView playView, View dividerView,
+            PhoneCallDetailsViews phoneCallDetailsViews, View standAloneItemView,
+            View standAloneHeaderView, TextView standAloneHeaderTextView) {
+        return new CallLogListItemViews(photoView, callView, playView, dividerView,
+                phoneCallDetailsViews, standAloneItemView, standAloneHeaderView,
+                standAloneHeaderTextView);
     }
 }
diff --git a/src/com/android/contacts/voicemail/VoicemailPlaybackFragment.java b/src/com/android/contacts/voicemail/VoicemailPlaybackFragment.java
index 328360b..436f13b 100644
--- a/src/com/android/contacts/voicemail/VoicemailPlaybackFragment.java
+++ b/src/com/android/contacts/voicemail/VoicemailPlaybackFragment.java
@@ -16,21 +16,23 @@
 
 package com.android.contacts.voicemail;
 
+import com.android.contacts.R;
+import com.android.ex.variablespeed.MediaPlayerProxy;
+import com.android.ex.variablespeed.VariableSpeed;
+
 import android.app.Fragment;
 import android.content.Context;
 import android.media.AudioManager;
 import android.net.Uri;
 import android.os.Bundle;
+import android.util.Log;
 import android.view.LayoutInflater;
 import android.view.View;
 import android.view.ViewGroup;
 import android.widget.ImageButton;
 import android.widget.SeekBar;
 import android.widget.TextView;
-
-import com.android.contacts.R;
-import com.android.ex.variablespeed.MediaPlayerProxy;
-import com.android.ex.variablespeed.VariableSpeed;
+import android.widget.Toast;
 
 import java.util.concurrent.ExecutorService;
 import java.util.concurrent.Executors;
@@ -50,6 +52,7 @@
  */
 @NotThreadSafe
 public class VoicemailPlaybackFragment extends Fragment {
+    private static final String TAG = "VoicemailPlayback";
     private static final int NUMBER_OF_THREADS_IN_POOL = 2;
 
     private VoicemailPlaybackPresenter mPresenter;
@@ -217,10 +220,14 @@
         }
 
         @Override
-        public void playbackError() {
+        public void playbackError(Exception e) {
+            mRateIncreaseButton.setEnabled(false);
+            mRateDecreaseButton.setEnabled(false);
             mStartStopButton.setEnabled(false);
             mPlaybackSeek.setProgress(0);
             mPlaybackSeek.setEnabled(false);
+            Toast.makeText(getActivity(), R.string.voicemail_playback_error, Toast.LENGTH_SHORT);
+            Log.e(TAG, "Could not play voicemail", e);
         }
 
         @Override
diff --git a/src/com/android/contacts/voicemail/VoicemailPlaybackPresenter.java b/src/com/android/contacts/voicemail/VoicemailPlaybackPresenter.java
index 11764c9..53e64e9 100644
--- a/src/com/android/contacts/voicemail/VoicemailPlaybackPresenter.java
+++ b/src/com/android/contacts/voicemail/VoicemailPlaybackPresenter.java
@@ -16,6 +16,9 @@
 
 package com.android.contacts.voicemail;
 
+import com.android.ex.variablespeed.MediaPlayerProxy;
+import com.android.ex.variablespeed.SingleThreadedMediaPlayerProxy;
+
 import android.content.Context;
 import android.media.MediaPlayer;
 import android.net.Uri;
@@ -23,9 +26,6 @@
 import android.view.View;
 import android.widget.SeekBar;
 
-import com.android.ex.variablespeed.MediaPlayerProxy;
-import com.android.ex.variablespeed.SingleThreadedMediaPlayerProxy;
-
 import java.io.IOException;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.ScheduledFuture;
@@ -61,7 +61,7 @@
         int getDesiredClipPosition();
         void playbackStarted();
         void playbackStopped();
-        void playbackError();
+        void playbackError(Exception e);
         boolean isSpeakerPhoneOn();
         void setSpeakerPhoneOn(boolean on);
         void finish();
@@ -216,7 +216,7 @@
     }
 
     private void handleError(Exception e) {
-        mView.playbackError();
+        mView.playbackError(e);
         mPlayer.release();
         mPositionUpdater.stopUpdating();
     }
diff --git a/tests/src/com/android/contacts/CallDetailActivityTest.java b/tests/src/com/android/contacts/CallDetailActivityTest.java
new file mode 100644
index 0000000..a36216e
--- /dev/null
+++ b/tests/src/com/android/contacts/CallDetailActivityTest.java
@@ -0,0 +1,119 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.contacts;
+
+import com.android.contacts.util.IntegrationTestUtils;
+import com.google.common.base.Preconditions;
+
+import android.app.Activity;
+import android.content.ContentResolver;
+import android.content.ContentUris;
+import android.content.ContentValues;
+import android.content.Intent;
+import android.net.Uri;
+import android.provider.CallLog;
+import android.test.ActivityInstrumentationTestCase2;
+
+/**
+ * Unit tests for the {@link CallDetailActivity}.
+ */
+public class CallDetailActivityTest extends ActivityInstrumentationTestCase2<CallDetailActivity> {
+    private static final String FAKE_VOICEMAIL_URI_STRING = "content://fake_uri";
+    private Uri mUri;
+    private IntegrationTestUtils mTestUtils;
+
+    public CallDetailActivityTest() {
+        super(CallDetailActivity.class);
+    }
+
+    @Override
+    protected void setUp() throws Exception {
+        super.setUp();
+        // I don't like the default of focus-mode for tests, the green focus border makes the
+        // screenshots look weak.
+        setActivityInitialTouchMode(true);
+        mTestUtils = new IntegrationTestUtils(getInstrumentation());
+    }
+
+    @Override
+    protected void tearDown() throws Exception {
+        cleanUpUri();
+        mTestUtils = null;
+        super.tearDown();
+    }
+
+    /**
+     * Test for bug where increase rate button with invalid voicemail causes a crash.
+     * <p>
+     * The repro steps for this crash were to open a voicemail that does not have an attachment,
+     * then click the play button (which just reported an error), then after that try to adjust the
+     * rate.
+     */
+    public void testClickIncreaseRateButtonWithInvalidVoicemailDoesNotCrash() throws Throwable {
+        setActivityIntentForTestVoicemailEntry();
+        Activity activity = getActivity();
+        mTestUtils.clickButton(activity, R.id.playback_start_stop);
+        mTestUtils.clickButton(activity, R.id.rate_increase_button);
+    }
+
+    /** Test for bug where missing Extras on intent used to start Activity causes NPE. */
+    public void testCallLogUriWithMissingExtrasShouldNotCauseNPE() throws Exception {
+        setActivityIntentForTestCallEntry();
+        getActivity();
+    }
+
+    private void setActivityIntentForTestCallEntry() {
+        createTestCallEntry(false);
+        setActivityIntent(new Intent(Intent.ACTION_VIEW, mUri));
+    }
+
+    private void setActivityIntentForTestVoicemailEntry() {
+        createTestCallEntry(true);
+        Intent intent = new Intent(Intent.ACTION_VIEW, mUri);
+        Uri voicemailUri = Uri.parse(FAKE_VOICEMAIL_URI_STRING);
+        intent.putExtra(CallDetailActivity.EXTRA_VOICEMAIL_URI, voicemailUri);
+        setActivityIntent(intent);
+    }
+
+    /** Inserts an entry into the call log. */
+    private void createTestCallEntry(boolean isVoicemail) {
+        Preconditions.checkState(mUri == null, "mUri should be null");
+        ContentResolver contentResolver = getContentResolver();
+        ContentValues contentValues = new ContentValues();
+        contentValues.put(CallLog.Calls.NUMBER, "01234567890");
+        if (isVoicemail) {
+            contentValues.put(CallLog.Calls.TYPE, CallLog.Calls.VOICEMAIL_TYPE);
+            contentValues.put(CallLog.Calls.VOICEMAIL_URI, FAKE_VOICEMAIL_URI_STRING);
+        } else {
+            contentValues.put(CallLog.Calls.TYPE, CallLog.Calls.INCOMING_TYPE);
+        }
+        contentValues.put(CallLog.Calls.VOICEMAIL_URI, FAKE_VOICEMAIL_URI_STRING);
+        mUri = contentResolver.insert(CallLog.Calls.CONTENT_URI_WITH_VOICEMAIL, contentValues);
+    }
+
+    private void cleanUpUri() {
+        if (mUri != null) {
+            getContentResolver().delete(CallLog.Calls.CONTENT_URI_WITH_VOICEMAIL,
+                    "_ID = ?", new String[] { String.valueOf(ContentUris.parseId(mUri)) });
+            mUri = null;
+        }
+    }
+
+    private ContentResolver getContentResolver() {
+        return getInstrumentation().getTargetContext().getContentResolver();
+    }
+}
diff --git a/tests/src/com/android/contacts/calllog/CallLogListItemHelperTest.java b/tests/src/com/android/contacts/calllog/CallLogListItemHelperTest.java
index c56041e..626d7c6 100644
--- a/tests/src/com/android/contacts/calllog/CallLogListItemHelperTest.java
+++ b/tests/src/com/android/contacts/calllog/CallLogListItemHelperTest.java
@@ -71,7 +71,7 @@
                 resources, callTypeHelper, mPhoneNumberHelper);
         mHelper = new CallLogListItemHelper(phoneCallDetailsHelper, mPhoneNumberHelper);
         mViews = CallLogListItemViews.createForTest(new QuickContactBadge(context),
-                new ImageView(context), new ImageView(context),
+                new ImageView(context), new ImageView(context), new View(context),
                 PhoneCallDetailsViews.createForTest(new TextView(context),
                         new LinearLayout(context), new TextView(context), new TextView(context),
                         new TextView(context), new TextView(context)),
@@ -93,20 +93,17 @@
 
     public void testSetPhoneCallDetails_Unknown() {
         setPhoneCallDetailsWithNumber(CallerInfo.UNKNOWN_NUMBER, CallerInfo.UNKNOWN_NUMBER);
-        assertEquals(View.INVISIBLE, mViews.callView.getVisibility());
-        assertEquals(View.GONE, mViews.playView.getVisibility());
+        assertNoCallButton();
     }
 
     public void testSetPhoneCallDetails_Private() {
         setPhoneCallDetailsWithNumber(CallerInfo.PRIVATE_NUMBER, CallerInfo.PRIVATE_NUMBER);
-        assertEquals(View.INVISIBLE, mViews.callView.getVisibility());
-        assertEquals(View.GONE, mViews.playView.getVisibility());
+        assertNoCallButton();
     }
 
     public void testSetPhoneCallDetails_Payphone() {
         setPhoneCallDetailsWithNumber(CallerInfo.PAYPHONE_NUMBER, CallerInfo.PAYPHONE_NUMBER);
-        assertEquals(View.INVISIBLE, mViews.callView.getVisibility());
-        assertEquals(View.GONE, mViews.playView.getVisibility());
+        assertNoCallButton();
     }
 
     public void testSetPhoneCallDetails_VoicemailNumber() {
@@ -121,11 +118,37 @@
         assertEquals(View.VISIBLE, mViews.playView.getVisibility());
     }
 
+    public void testSetPhoneCallDetails_VoicemailFromUnknown() {
+        setPhoneCallDetailsWithNumberAndType(CallerInfo.UNKNOWN_NUMBER, CallerInfo.UNKNOWN_NUMBER,
+                Calls.VOICEMAIL_TYPE);
+        assertEquals(View.VISIBLE, mViews.playView.getVisibility());
+        assertEmptyCallButton();
+    }
+
+    /** Asserts that the whole call area is gone. */
+    private void assertNoCallButton() {
+        assertEquals(View.GONE, mViews.callView.getVisibility());
+        assertEquals(View.GONE, mViews.playView.getVisibility());
+        assertEquals(View.GONE, mViews.dividerView.getVisibility());
+    }
+
+    /** Asserts that the call area is present but empty. */
+    private void assertEmptyCallButton() {
+        assertEquals(View.INVISIBLE, mViews.callView.getVisibility());
+        assertEquals(View.VISIBLE, mViews.dividerView.getVisibility());
+    }
+
     /** Sets the details of a phone call using the specified phone number. */
     private void setPhoneCallDetailsWithNumber(String number, String formattedNumber) {
+        setPhoneCallDetailsWithNumberAndType(number, formattedNumber, Calls.INCOMING_TYPE);
+    }
+
+    /** Sets the details of a phone call using the specified phone number. */
+    private void setPhoneCallDetailsWithNumberAndType(String number, String formattedNumber,
+            int callType) {
         mHelper.setPhoneCallDetails(mViews,
                 new PhoneCallDetails(number, formattedNumber, TEST_COUNTRY_ISO,
-                        new int[]{ Calls.INCOMING_TYPE }, TEST_DATE, TEST_DURATION),
+                        new int[]{ callType }, TEST_DATE, TEST_DURATION),
                 true, false);
     }
 
diff --git a/tests/src/com/android/contacts/util/IntegrationTestUtils.java b/tests/src/com/android/contacts/util/IntegrationTestUtils.java
new file mode 100644
index 0000000..9ce60a0
--- /dev/null
+++ b/tests/src/com/android/contacts/util/IntegrationTestUtils.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 2011 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package com.android.contacts.util;
+
+import android.app.Activity;
+import android.app.Instrumentation;
+import android.view.View;
+
+import junit.framework.Assert;
+
+import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.FutureTask;
+
+/** Some utility methods for making integration testing smoother. */
+public class IntegrationTestUtils {
+    private final Instrumentation mInstrumentation;
+
+    public IntegrationTestUtils(Instrumentation instrumentation) {
+        mInstrumentation = instrumentation;
+    }
+
+    /**
+     * Find a view by a given resource id, from the given activity, and click it, iff it is
+     * enabled according to {@link View#isEnabled()}.
+     */
+    public void clickButton(final Activity activity, final int buttonResourceId) throws Throwable {
+        runOnUiThreadAndGetTheResult(new Callable<Void>() {
+            @Override
+            public Void call() throws Exception {
+                View view = activity.findViewById(buttonResourceId);
+                Assert.assertNotNull(view);
+                if (view.isEnabled()) {
+                    view.performClick();
+                }
+                return null;
+            }
+        });
+    }
+
+    // TODO: Move this class and the appropriate documentation into a test library, having checked
+    // first to see if exactly this code already exists or not.
+    /**
+     * Execute a callable on the ui thread, returning its result synchronously.
+     * <p>
+     * Waits for an idle sync on the main thread (see {@link Instrumentation#waitForIdle(Runnable)})
+     * before executing this callable.
+     */
+    private <T> T runOnUiThreadAndGetTheResult(Callable<T> callable) throws Throwable {
+        FutureTask<T> future = new FutureTask<T>(callable);
+        mInstrumentation.waitForIdle(future);
+        try {
+            return future.get();
+        } catch (ExecutionException e) {
+            // Unwrap the cause of the exception and re-throw it.
+            throw e.getCause();
+        }
+    }
+}