Merge "Translate FAB up and down when Snackbar appears and disappears." into ub-contactsdialer-a-dev
diff --git a/res/layout/voicemail_playback_layout.xml b/res/layout/voicemail_playback_layout.xml
index 555d201..54493f1 100644
--- a/res/layout/voicemail_playback_layout.xml
+++ b/res/layout/voicemail_playback_layout.xml
@@ -71,7 +71,7 @@
 
                 <ImageButton android:id="@+id/playback_speakerphone"
                     style="@style/VoicemailPlaybackLayoutButtonStyle"
-                    android:src="@drawable/ic_speakerphone_on"
+                    android:src="@drawable/ic_volume_down_24dp"
                     android:tint="@color/voicemail_icon_tint"
                     android:contentDescription="@string/description_playback_speakerphone" />
 
diff --git a/src/com/android/dialer/DialtactsActivity.java b/src/com/android/dialer/DialtactsActivity.java
index 6d8ed61..d5dfa94 100644
--- a/src/com/android/dialer/DialtactsActivity.java
+++ b/src/com/android/dialer/DialtactsActivity.java
@@ -118,10 +118,6 @@
 
     public static final String SHARED_PREFS_NAME = "com.android.dialer_preferences";
 
-    /** @see #getCallOrigin() */
-    private static final String CALL_ORIGIN_DIALTACTS =
-            "com.android.dialer.DialtactsActivity";
-
     private static final String KEY_IN_REGULAR_SEARCH_UI = "in_regular_search_ui";
     private static final String KEY_IN_DIALPAD_SEARCH_UI = "in_dialpad_search_ui";
     private static final String KEY_SEARCH_QUERY = "search_query";
@@ -536,13 +532,21 @@
         mDialerDatabaseHelper.startSmartDialUpdateThread();
         mFloatingActionButtonController.align(getFabAlignment(), false /* animate */);
 
-        if (getIntent().hasExtra(EXTRA_SHOW_TAB)) {
+        if (Calls.CONTENT_TYPE.equals(getIntent().getType())) {
+            // Externally specified extras take precedence to EXTRA_SHOW_TAB, which is only
+            // used internally.
+            final Bundle extras = getIntent().getExtras();
+            if (extras != null
+                    && extras.getInt(Calls.EXTRA_CALL_TYPE_FILTER) == Calls.VOICEMAIL_TYPE) {
+                mListsFragment.showTab(ListsFragment.TAB_INDEX_VOICEMAIL);
+            } else {
+                mListsFragment.showTab(ListsFragment.TAB_INDEX_HISTORY);
+            }
+        } else if (getIntent().hasExtra(EXTRA_SHOW_TAB)) {
             int index = getIntent().getIntExtra(EXTRA_SHOW_TAB, ListsFragment.TAB_INDEX_SPEED_DIAL);
             if (index < mListsFragment.getTabCount()) {
                 mListsFragment.showTab(index);
             }
-        } else if (Calls.CONTENT_TYPE.equals(getIntent().getType())) {
-            mListsFragment.showTab(ListsFragment.TAB_INDEX_HISTORY);
         }
 
         setSearchBoxHint();
@@ -951,16 +955,6 @@
     }
 
     /**
-     * Returns an appropriate call origin for this Activity. May return null when no call origin
-     * should be used (e.g. when some 3rd party application launched the screen. Call origin is
-     * for remembering the tab in which the user made a phone call, so the external app's DIAL
-     * request should not be counted.)
-     */
-    public String getCallOrigin() {
-        return !isDialIntent(getIntent()) ? CALL_ORIGIN_DIALTACTS : null;
-    }
-
-    /**
      * Shows the search fragment
      */
     private void enterSearchUi(boolean smartDialSearch, String query, boolean animate) {
@@ -1252,7 +1246,7 @@
         // Specify call-origin so that users will see the previous tab instead of
         // CallLog screen (search UI will be automatically exited).
         PhoneNumberInteraction.startInteractionForPhoneCall(
-                DialtactsActivity.this, dataUri, getCallOrigin());
+                DialtactsActivity.this, dataUri, null);
         mClearSearchOnPause = true;
     }
 
@@ -1269,8 +1263,8 @@
             phoneNumber = "";
         }
         Intent intent = isVideoCall ?
-                IntentUtil.getVideoCallIntent(phoneNumber, getCallOrigin()) :
-                IntentUtil.getCallIntent(phoneNumber, getCallOrigin());
+                IntentUtil.getVideoCallIntent(phoneNumber, (String) null) :
+                IntentUtil.getCallIntent(phoneNumber, (String) null);
         DialerUtils.startActivityWithErrorToast(this, intent);
         mClearSearchOnPause = true;
     }
diff --git a/src/com/android/dialer/calllog/ContactInfoHelper.java b/src/com/android/dialer/calllog/ContactInfoHelper.java
index 2e07a03..2f97bc5 100644
--- a/src/com/android/dialer/calllog/ContactInfoHelper.java
+++ b/src/com/android/dialer/calllog/ContactInfoHelper.java
@@ -75,30 +75,22 @@
         if (TextUtils.isEmpty(number)) {
             return null;
         }
-        final ContactInfo info;
 
-        // Determine the contact info.
+        ContactInfo info;
+
         if (PhoneNumberHelper.isUriNumber(number)) {
-            // This "number" is really a SIP address.
-            ContactInfo sipInfo = queryContactInfoForSipAddress(number);
-            if (sipInfo == null || sipInfo == ContactInfo.EMPTY) {
-                // Check whether the "username" part of the SIP address is
-                // actually the phone number of a contact.
+            // The number is a SIP address..
+            info = lookupContactFromUri(getContactInfoLookupUri(number));
+            if (info == null || info == ContactInfo.EMPTY) {
+                // If lookup failed, check if the "username" of the SIP address is a phone number.
                 String username = PhoneNumberHelper.getUsernameFromUriNumber(number);
                 if (PhoneNumberUtils.isGlobalPhoneNumber(username)) {
-                    sipInfo = queryContactInfoForPhoneNumber(username, countryIso);
+                    info = queryContactInfoForPhoneNumber(username, countryIso);
                 }
             }
-            info = sipInfo;
         } else {
             // Look for a contact that has the given phone number.
-            ContactInfo phoneInfo = queryContactInfoForPhoneNumber(number, countryIso);
-
-            if (phoneInfo == null || phoneInfo == ContactInfo.EMPTY) {
-                // Check whether the phone number has been saved as an "Internet call" number.
-                phoneInfo = queryContactInfoForSipAddress(number);
-            }
-            info = phoneInfo;
+            info = queryContactInfoForPhoneNumber(number, countryIso);
         }
 
         final ContactInfo updatedInfo;
@@ -201,28 +193,6 @@
     }
 
     /**
-     * Determines the contact information for the given SIP address.
-     * <p>
-     * It returns the contact info if found.
-     * <p>
-     * If no contact corresponds to the given SIP address, returns {@link ContactInfo#EMPTY}.
-     * <p>
-     * If the lookup fails for some other reason, it returns null.
-     */
-    private ContactInfo queryContactInfoForSipAddress(String sipAddress) {
-        if (TextUtils.isEmpty(sipAddress)) {
-            return null;
-        }
-        final ContactInfo info;
-
-        // "contactNumber" is a SIP address, so use the PhoneLookup table with the SIP parameter.
-        Uri.Builder uriBuilder = PhoneLookup.ENTERPRISE_CONTENT_FILTER_URI.buildUpon();
-        uriBuilder.appendPath(Uri.encode(sipAddress));
-        uriBuilder.appendQueryParameter(PhoneLookup.QUERY_PARAMETER_SIP_ADDRESS, "1");
-        return lookupContactFromUri(uriBuilder.build());
-    }
-
-    /**
      * Determines the contact information for the given phone number.
      * <p>
      * It returns the contact info if found.
@@ -235,21 +205,8 @@
         if (TextUtils.isEmpty(number)) {
             return null;
         }
-        String contactNumber = number;
-        if (!TextUtils.isEmpty(countryIso)) {
-            // Normalize the number: this is needed because the PhoneLookup query below does not
-            // accept a country code as an input.
-            String numberE164 = PhoneNumberUtils.formatNumberToE164(number, countryIso);
-            if (!TextUtils.isEmpty(numberE164)) {
-                // Only use it if the number could be formatted to E164.
-                contactNumber = numberE164;
-            }
-        }
 
-        // The "contactNumber" is a regular phone number, so use the PhoneLookup table.
-        Uri uri = Uri.withAppendedPath(PhoneLookup.ENTERPRISE_CONTENT_FILTER_URI,
-                Uri.encode(contactNumber));
-        ContactInfo info = lookupContactFromUri(uri);
+        ContactInfo info = lookupContactFromUri(getContactInfoLookupUri(number));
         if (info != null && info != ContactInfo.EMPTY) {
             info.formattedNumber = formatPhoneNumber(number, null, countryIso);
         } else if (mCachedNumberLookupService != null) {
@@ -393,6 +350,16 @@
         }
     }
 
+    public static Uri getContactInfoLookupUri(String number) {
+        // Get URI for the number in the PhoneLookup table, with a parameter to indicate whether
+        // the number is a SIP number.
+        return PhoneLookup.ENTERPRISE_CONTENT_FILTER_URI.buildUpon()
+                .appendPath(Uri.encode(number))
+                .appendQueryParameter(PhoneLookup.QUERY_PARAMETER_SIP_ADDRESS,
+                        String.valueOf(PhoneNumberHelper.isUriNumber(number)))
+                .build();
+    }
+
     /**
      * Returns the contact information stored in an entry of the call log.
      *
diff --git a/src/com/android/dialer/dialpad/DialpadFragment.java b/src/com/android/dialer/dialpad/DialpadFragment.java
index 0bbf802..c35bdea 100644
--- a/src/com/android/dialer/dialpad/DialpadFragment.java
+++ b/src/com/android/dialer/dialpad/DialpadFragment.java
@@ -1140,9 +1140,7 @@
                 // Clear the digits just in case.
                 clearDialpad();
             } else {
-                final Intent intent = IntentUtil.getCallIntent(number,
-                        (getActivity() instanceof DialtactsActivity ?
-                                ((DialtactsActivity) getActivity()).getCallOrigin() : null));
+                final Intent intent = IntentUtil.getCallIntent(number, (String) null);
                 DialerUtils.startActivityWithErrorToast(getActivity(), intent);
                 hideAndClearDialpad(false);
             }
diff --git a/src/com/android/dialer/interactions/PhoneNumberInteraction.java b/src/com/android/dialer/interactions/PhoneNumberInteraction.java
index 6e218c0..601a9c7 100644
--- a/src/com/android/dialer/interactions/PhoneNumberInteraction.java
+++ b/src/com/android/dialer/interactions/PhoneNumberInteraction.java
@@ -521,7 +521,17 @@
 
     @VisibleForTesting
     /* package */ void showDisambiguationDialog(ArrayList<PhoneItem> phoneList) {
-        PhoneDisambiguationDialogFragment.show(((Activity)mContext).getFragmentManager(),
-                phoneList, mInteractionType, mCallOrigin);
+        final Activity activity = (Activity) mContext;
+        if (activity.isDestroyed()) {
+            // Check whether the activity is still running
+            return;
+        }
+        try {
+            PhoneDisambiguationDialogFragment.show(activity.getFragmentManager(),
+                    phoneList, mInteractionType, mCallOrigin);
+        } catch (IllegalStateException e) {
+            // ignore to be safe. Shouldn't happen because we checked the
+            // activity wasn't destroyed, but to be safe.
+        }
     }
 }
diff --git a/src/com/android/dialer/list/ListsFragment.java b/src/com/android/dialer/list/ListsFragment.java
index 09a4cb2..c80ab42 100644
--- a/src/com/android/dialer/list/ListsFragment.java
+++ b/src/com/android/dialer/list/ListsFragment.java
@@ -176,10 +176,6 @@
         Trace.beginSection(TAG + " onCreate");
         super.onCreate(savedInstanceState);
 
-        Trace.beginSection(TAG + " getCurrentCountryIso");
-        final String currentCountryIso = GeoUtil.getCurrentCountryIso(getActivity());
-        Trace.endSection();
-
         mVoicemailStatusHelper = new VoicemailStatusHelperImpl();
         mHasFetchedVoicemailStatus = false;
 
@@ -265,7 +261,7 @@
                 // Try to show the voicemail tab after the voicemail status returns.
                 mShowVoicemailTabAfterVoicemailStatusIsFetched = true;
             }
-        } else {
+        } else if (index < getTabCount()){
             mViewPager.setCurrentItem(getRtlPosition(index));
         }
     }
diff --git a/src/com/android/dialer/logging/Logger.java b/src/com/android/dialer/logging/Logger.java
new file mode 100644
index 0000000..3007077
--- /dev/null
+++ b/src/com/android/dialer/logging/Logger.java
@@ -0,0 +1,58 @@
+/*
+ * Copyright (C) 2015 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.dialer.logging;
+
+import android.app.Activity;
+
+import com.android.dialerbind.ObjectFactory;
+import com.android.incallui.Call;
+
+public abstract class Logger {
+
+    public static Logger getInstance() {
+        return ObjectFactory.getLoggerInstance();
+    }
+
+    /**
+     * Logs a call event. PII like the call's number or caller details should never be logged.
+     *
+     * @param call to log.
+     */
+    public static void logCall(Call call) {
+        final Logger logger = getInstance();
+        if (logger != null) {
+            logger.logCallImpl(call);
+        }
+    }
+
+    /**
+     * Logs an event indicating that a screen/fragment was displayed.
+     *
+     * @param fragmentName of the displayed fragment.
+     * @param activity Parent activity of the fragment.
+     * @param tag Optional string used to provide additional information about the fragment.
+     */
+    public static void logScreenView(String fragmentName, Activity activity, String tag) {
+        final Logger logger = getInstance();
+        if (logger != null) {
+            logger.logScreenViewImpl(fragmentName, activity, tag);
+        }
+    }
+
+    public abstract void logCallImpl(Call call);
+    public abstract void logScreenViewImpl(String fragmentName, Activity activity, String tag);
+}
diff --git a/src/com/android/dialer/voicemail/VoicemailPlaybackLayout.java b/src/com/android/dialer/voicemail/VoicemailPlaybackLayout.java
index 69c075f..133da36 100644
--- a/src/com/android/dialer/voicemail/VoicemailPlaybackLayout.java
+++ b/src/com/android/dialer/voicemail/VoicemailPlaybackLayout.java
@@ -159,7 +159,7 @@
         @Override
         public void onClick(View v) {
             if (mPresenter != null) {
-                onSpeakerphoneOn(!mPresenter.isSpeakerphoneOn());
+                mPresenter.toggleSpeakerphone();
             }
         }
     };
@@ -286,10 +286,6 @@
 
         mStartStopButton.setImageResource(R.drawable.ic_pause);
 
-        if (mPresenter != null) {
-            onSpeakerphoneOn(mPresenter.isSpeakerphoneOn());
-        }
-
         if (mPositionUpdater != null) {
             mPositionUpdater.stopUpdating();
             mPositionUpdater = null;
@@ -321,10 +317,6 @@
     }
 
     public void onSpeakerphoneOn(boolean on) {
-        if (mPresenter != null) {
-            mPresenter.setSpeakerphoneOn(on);
-        }
-
         if (on) {
             mPlaybackSpeakerphone.setImageResource(R.drawable.ic_volume_up_24dp);
             // Speaker is now on, tapping button will turn it off.
@@ -373,7 +365,6 @@
     @Override
     public void disableUiElements() {
         mStartStopButton.setEnabled(false);
-        mPlaybackSpeakerphone.setEnabled(false);
         mPlaybackSeek.setProgress(0);
         mPlaybackSeek.setEnabled(false);
 
@@ -384,7 +375,6 @@
     @Override
     public void enableUiElements() {
         mStartStopButton.setEnabled(true);
-        mPlaybackSpeakerphone.setEnabled(true);
         mPlaybackSeek.setEnabled(true);
 
         mPositionText.setVisibility(View.VISIBLE);
diff --git a/src/com/android/dialer/voicemail/VoicemailPlaybackPresenter.java b/src/com/android/dialer/voicemail/VoicemailPlaybackPresenter.java
index 3f5a489..e6ab267 100644
--- a/src/com/android/dialer/voicemail/VoicemailPlaybackPresenter.java
+++ b/src/com/android/dialer/voicemail/VoicemailPlaybackPresenter.java
@@ -60,7 +60,7 @@
  * {@link CallLogFragment} and {@link CallLogAdapter}.
  * <p>
  * This controls a single {@link com.android.dialer.voicemail.VoicemailPlaybackLayout}. A single
- * instance can be reused for different such layouts, using {@link #setVoicemailPlaybackView}. This
+ * instance can be reused for different such layouts, using {@link #setPlaybackView}. This
  * is to facilitate reuse across different voicemail call log entries.
  * <p>
  * This class is not thread safe. The thread policy for this class is thread-confinement, all calls
@@ -120,6 +120,8 @@
     // If present in the saved instance bundle, indicates where to set the playback slider.
     private static final String CLIP_POSITION_KEY =
             VoicemailPlaybackPresenter.class.getName() + ".CLIP_POSITION_KEY";
+    private static final String IS_SPEAKERPHONE_ON_KEY =
+            VoicemailPlaybackPresenter.class.getName() + ".IS_SPEAKER_PHONE_ON";
 
     /**
      * The most recently cached duration. We cache this since we don't want to keep requesting it
@@ -141,6 +143,7 @@
     // MediaPlayer crashes on some method calls if not prepared but does not have a method which
     // exposes its prepared state. Store this locally, so we can check and prevent crashes.
     private boolean mIsPrepared;
+    private boolean mIsSpeakerphoneOn;
 
     private boolean mShouldResumePlaybackAfterSeeking;
     private int mInitialOrientation;
@@ -211,6 +214,7 @@
             mIsPrepared = savedInstanceState.getBoolean(IS_PREPARED_KEY);
             mPosition = savedInstanceState.getInt(CLIP_POSITION_KEY, 0);
             mIsPlaying = savedInstanceState.getBoolean(IS_PLAYING_STATE_KEY, false);
+            mIsSpeakerphoneOn = savedInstanceState.getBoolean(IS_SPEAKERPHONE_ON_KEY, false);
         }
 
         if (mMediaPlayer == null) {
@@ -228,6 +232,7 @@
             outState.putBoolean(IS_PREPARED_KEY, mIsPrepared);
             outState.putInt(CLIP_POSITION_KEY, mView.getDesiredClipPosition());
             outState.putBoolean(IS_PLAYING_STATE_KEY, mIsPlaying);
+            outState.putBoolean(IS_SPEAKERPHONE_ON_KEY, mIsSpeakerphoneOn);
         }
     }
 
@@ -239,16 +244,21 @@
         mView = view;
         mView.setPresenter(this, voicemailUri);
 
+        // Handles cases where the same entry is binded again when scrolling in list, or where
+        // the MediaPlayer was retained after an orientation change.
         if (mMediaPlayer != null && mIsPrepared && voicemailUri.equals(mVoicemailUri)) {
-            // Handles case where MediaPlayer was retained after an orientation change.
             onPrepared(mMediaPlayer);
-            mView.onSpeakerphoneOn(isSpeakerphoneOn());
         } else {
             if (!voicemailUri.equals(mVoicemailUri)) {
+                mVoicemailUri = voicemailUri;
                 mPosition = 0;
+                // Default to earpiece.
+                setSpeakerphoneOn(false);
+            } else {
+                // Update the view to the current speakerphone state.
+                mView.onSpeakerphoneOn(mIsSpeakerphoneOn);
             }
 
-            mVoicemailUri = voicemailUri;
             mDuration.set(0);
 
             if (startPlayingImmediately) {
@@ -258,9 +268,6 @@
                 mIsPlaying = startPlayingImmediately;
                 checkForContent();
             }
-
-            // Default to earpiece.
-            mView.onSpeakerphoneOn(false);
         }
     }
 
@@ -595,7 +602,6 @@
             // If we haven't downloaded the voicemail yet, attempt to download it.
             checkForContent();
             mIsPlaying = true;
-
             return;
         }
 
@@ -616,6 +622,7 @@
                     throw new RejectedExecutionException("Could not capture audio focus.");
                 }
 
+                setSpeakerphoneOn(mIsSpeakerphoneOn);
                 // Can throw RejectedExecutionException.
                 mMediaPlayer.start();
             } catch (RejectedExecutionException e) {
@@ -625,11 +632,6 @@
 
         Log.d(TAG, "Resumed playback at " + mPosition + ".");
         mView.onPlaybackStarted(mDuration.get(), getScheduledExecutorServiceInstance());
-        if (isSpeakerphoneOn()) {
-            mActivity.getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON);
-        } else {
-            enableProximitySensor();
-        }
     }
 
     /**
@@ -681,7 +683,7 @@
     }
 
     private void enableProximitySensor() {
-        if (mProximityWakeLock == null || isSpeakerphoneOn() || !mIsPrepared
+        if (mProximityWakeLock == null || mIsSpeakerphoneOn || !mIsPrepared
                 || mMediaPlayer == null || !mMediaPlayer.isPlaying()) {
             return;
         }
@@ -707,24 +709,32 @@
         }
     }
 
-    public void setSpeakerphoneOn(boolean on) {
-        mAudioManager.setSpeakerphoneOn(on);
-
-        if (on) {
-            disableProximitySensor(false /* waitForFarState */);
-            if (mIsPrepared && mMediaPlayer != null && mMediaPlayer.isPlaying()) {
-                mActivity.getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON);
-            }
-        } else {
-            enableProximitySensor();
-            if (mActivity != null) {
-                mActivity.getWindow().clearFlags(LayoutParams.FLAG_KEEP_SCREEN_ON);
-            }
-        }
+    public void toggleSpeakerphone() {
+        setSpeakerphoneOn(!mIsSpeakerphoneOn);
     }
 
-    public boolean isSpeakerphoneOn() {
-        return mAudioManager.isSpeakerphoneOn();
+    private void setSpeakerphoneOn(boolean on) {
+        mView.onSpeakerphoneOn(on);
+        if (mIsSpeakerphoneOn == on) {
+            return;
+        }
+
+        mIsSpeakerphoneOn = on;
+        mAudioManager.setSpeakerphoneOn(mIsSpeakerphoneOn);
+
+        if (mIsPlaying) {
+            if (on) {
+                disableProximitySensor(false /* waitForFarState */);
+                if (mIsPrepared && mMediaPlayer != null && mMediaPlayer.isPlaying()) {
+                    mActivity.getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON);
+                }
+            } else {
+                enableProximitySensor();
+                if (mActivity != null) {
+                    mActivity.getWindow().clearFlags(LayoutParams.FLAG_KEEP_SCREEN_ON);
+                }
+            }
+        }
     }
 
     public void setOnVoicemailDeletedListener(OnVoicemailDeletedListener listener) {
@@ -767,4 +777,9 @@
     public boolean isPlaying() {
         return mIsPlaying;
     }
+
+    @VisibleForTesting
+    public boolean isSpeakerphoneOn() {
+        return mIsSpeakerphoneOn;
+    }
 }
diff --git a/src/com/android/dialerbind/ObjectFactory.java b/src/com/android/dialerbind/ObjectFactory.java
index d67ada0..c64afe8 100644
--- a/src/com/android/dialerbind/ObjectFactory.java
+++ b/src/com/android/dialerbind/ObjectFactory.java
@@ -22,6 +22,7 @@
 
 import com.android.dialer.calllog.CallLogAdapter;
 import com.android.dialer.calllog.ContactInfoHelper;
+import com.android.dialer.logging.Logger;
 import com.android.dialer.service.CachedNumberLookupService;
 import com.android.dialer.voicemail.VoicemailPlaybackPresenter;
 
@@ -59,4 +60,9 @@
                 voicemailPlaybackPresenter,
                 isCallLogActivity);
     }
+
+    public static Logger getLoggerInstance() {
+        // no-op
+        return null;
+    }
 }
diff --git a/tests/src/com/android/dialer/calllog/CallLogAdapterTest.java b/tests/src/com/android/dialer/calllog/CallLogAdapterTest.java
index 5c2588a..de6f198 100644
--- a/tests/src/com/android/dialer/calllog/CallLogAdapterTest.java
+++ b/tests/src/com/android/dialer/calllog/CallLogAdapterTest.java
@@ -16,25 +16,37 @@
 
 package com.android.dialer.calllog;
 
+import android.content.ContentUris;
 import android.content.Context;
+import android.content.Intent;
 import android.database.MatrixCursor;
+import android.net.Uri;
+import android.provider.CallLog.Calls;
+import android.provider.VoicemailContract;
 import android.support.v7.widget.RecyclerView.ViewHolder;
 import android.test.AndroidTestCase;
 import android.test.suitebuilder.annotation.SmallTest;
+import android.test.suitebuilder.annotation.MediumTest;
+import android.text.TextUtils;
 import android.view.View;
 import android.widget.LinearLayout;
 
 import com.android.dialer.contactinfo.ContactInfoCache;
 import com.android.dialer.contactinfo.ContactInfoCache.OnContactInfoChangedListener;
+import com.android.dialer.util.TestConstants;
 import com.google.common.collect.Lists;
 
+import java.util.Date;
 import java.util.List;
+import java.util.Random;
 
 /**
  * Unit tests for {@link CallLogAdapter}.
  */
 @SmallTest
 public class CallLogAdapterTest extends AndroidTestCase {
+    private static final int NO_VALUE_SET = -1;
+
     private static final String TEST_NUMBER_1 = "12345678";
     private static final String TEST_NUMBER_2 = "87654321";
     private static final String TEST_NUMBER_3 = "18273645";
@@ -43,16 +55,21 @@
     private static final int TEST_NUMBER_TYPE = 1;
     private static final String TEST_COUNTRY_ISO = "US";
 
-    /** The object under test. */
+    // The object under test.
     private TestCallLogAdapter mAdapter;
 
     private MatrixCursor mCursor;
+    private int mCursorSize;
+
     private View mView;
     private CallLogListItemViewHolder mViewHolder;
+    private Random mRandom;
 
     @Override
     protected void setUp() throws Exception {
         super.setUp();
+        mRandom = new Random();
+
         // Use a call fetcher that does not do anything.
         CallLogAdapter.CallFetcher fakeCallFetcher = new CallLogAdapter.CallFetcher() {
             @Override
@@ -88,8 +105,62 @@
         super.tearDown();
     }
 
+    @MediumTest
+    public void testBindView_NumberOnlyNoCache() {
+        createCallLogEntry();
+        mAdapter.changeCursor(mCursor);
+
+        mAdapter.onBindViewHolder(mViewHolder, 0);
+        assertNameIs(mViewHolder, TEST_NUMBER_1);
+    }
+
+    @MediumTest
+    public void testBindView_PrivateCall() {
+        createPrivateCallLogEntry();
+        mAdapter.changeCursor(mCursor);
+
+        mAdapter.onBindViewHolder(mViewHolder, 0);
+        assertEquals(Calls.PRESENTATION_RESTRICTED, mViewHolder.numberPresentation);
+    }
+
+    @MediumTest
+    public void testBindView_WithoutQuickContactBadge() {
+        createCallLogEntry();
+        mAdapter.changeCursor(mCursor);
+
+        mAdapter.onBindViewHolder(mViewHolder, 0);
+        assertFalse(mViewHolder.quickContactView.isEnabled());
+    }
+
+    @MediumTest
+    public void testBindView_CallButton() {
+        createCallLogEntry();
+        mAdapter.changeCursor(mCursor);
+
+        mAdapter.onBindViewHolder(mViewHolder, 0);
+
+        // The primaryActionView tag is set when the ViewHolder is binded. If it is possible
+        // to place a call to the phone number, a call intent will have been created which
+        // starts a phone call to the entry's number.
+        IntentProvider intentProvider =
+                (IntentProvider) mViewHolder.primaryActionButtonView.getTag();
+        Intent intent = intentProvider.getIntent(getContext());
+        assertEquals(TestConstants.CALL_INTENT_ACTION, intent.getAction());
+        assertEquals(Uri.parse("tel:" + TEST_NUMBER_1), intent.getData());
+    }
+
+    @MediumTest
+    public void testBindView_VoicemailUri() {
+        createVoicemailCallLogEntry();
+        mAdapter.changeCursor(mCursor);
+
+        mAdapter.onBindViewHolder(mViewHolder, 0);
+        assertEquals(Uri.parse(mViewHolder.voicemailUri),
+                ContentUris.withAppendedId(VoicemailContract.Voicemails.CONTENT_URI, 0));
+    }
+
     public void testBindView_NoCallLogCacheNorMemoryCache_EnqueueRequest() {
-        mCursor.addRow(createCallLogEntry());
+        createCallLogEntry();
 
         // Bind the views of a single row.
         mAdapter.changeCursor(mCursor);
@@ -126,7 +197,7 @@
 
 
     public void testBindView_NoCallLogButMemoryCache_EnqueueRequest() {
-        mCursor.addRow(createCallLogEntry());
+        createCallLogEntry();
         mAdapter.injectContactInfoForTest(TEST_NUMBER_1, TEST_COUNTRY_ISO, createContactInfo());
 
         // Bind the views of a single row.
@@ -174,12 +245,12 @@
     }
 
     public void testBindVoicemailPromoCard() {
-        mCursor.addRow(createCallLogEntry(TEST_NUMBER_1));
-        mCursor.addRow(createCallLogEntry(TEST_NUMBER_1));
-        mCursor.addRow(createCallLogEntry(TEST_NUMBER_2));
-        mCursor.addRow(createCallLogEntry(TEST_NUMBER_2));
-        mCursor.addRow(createCallLogEntry(TEST_NUMBER_2));
-        mCursor.addRow(createCallLogEntry(TEST_NUMBER_3));
+        createCallLogEntry(TEST_NUMBER_1);
+        createCallLogEntry(TEST_NUMBER_1);
+        createCallLogEntry(TEST_NUMBER_2);
+        createCallLogEntry(TEST_NUMBER_2);
+        createCallLogEntry(TEST_NUMBER_2);
+        createCallLogEntry(TEST_NUMBER_3);
 
         // Bind the voicemail promo card.
         mAdapter.showVoicemailPromoCard(true);
@@ -211,29 +282,80 @@
     }
 
     /** Returns a call log entry without cached values. */
-    private Object[] createCallLogEntry() {
-        return createCallLogEntry(TEST_NUMBER_1);
+    private void createCallLogEntry() {
+        createCallLogEntry(TEST_NUMBER_1);
     }
 
-    private Object[] createCallLogEntry(String testNumber) {
+    private void  createCallLogEntry(String testNumber) {
+        createCallLogEntry(testNumber, NO_VALUE_SET, NO_VALUE_SET, NO_VALUE_SET, NO_VALUE_SET);
+    }
+
+    private void createPrivateCallLogEntry() {
+        createCallLogEntry("", Calls.PRESENTATION_RESTRICTED, NO_VALUE_SET, 0, Calls.INCOMING_TYPE);
+    }
+
+    private void createVoicemailCallLogEntry() {
+        createCallLogEntry(TEST_NUMBER_1, NO_VALUE_SET, NO_VALUE_SET, NO_VALUE_SET,
+                Calls.VOICEMAIL_TYPE, true /* isVoicemail */);
+    }
+
+    private void createCallLogEntry(
+            String number, int presentation, long date, int duration, int type) {
+        createCallLogEntry(number, presentation, date, duration, type, false /* isVoicemail */);
+    }
+
+    private void createCallLogEntry(
+            String number,
+            int presentation,
+            long date,
+            int duration,
+            int type,
+            boolean isVoicemail) {
         Object[] values = CallLogQueryTestUtils.createTestValues();
-        values[CallLogQuery.NUMBER] = testNumber;
+
+        values[CallLogQuery.ID] = mCursorSize;
         values[CallLogQuery.COUNTRY_ISO] = TEST_COUNTRY_ISO;
-        return values;
+        values[CallLogQuery.DATE] = date != NO_VALUE_SET ? date : new Date().getTime();
+
+        if (!TextUtils.isEmpty(number)) {
+            values[CallLogQuery.NUMBER] = number;
+        }
+        if (presentation != NO_VALUE_SET) {
+            values[CallLogQuery.NUMBER_PRESENTATION] = presentation;
+        }
+        if (duration != NO_VALUE_SET) {
+            values[CallLogQuery.DURATION] = (duration < 0) ? mRandom.nextInt(10 * 60) : duration;
+        }
+        if (type != NO_VALUE_SET) {
+            values[CallLogQuery.CALL_TYPE] = type;
+        }
+        if (isVoicemail) {
+            values[CallLogQuery.VOICEMAIL_URI] =
+                ContentUris.withAppendedId(VoicemailContract.Voicemails.CONTENT_URI, mCursorSize);
+        }
+
+        mCursor.addRow(values);
+        mCursorSize++;
     }
 
-    /** Returns a call log entry with a cached values. */
+    // Returns a call log entry with a cached values.
     private Object[] createCallLogEntryWithCachedValues() {
-        Object[] values = createCallLogEntry();
+        Object[] values = CallLogQueryTestUtils.createTestValues();
+        values[CallLogQuery.NUMBER] = TEST_NUMBER_1;
+        values[CallLogQuery.COUNTRY_ISO] = TEST_COUNTRY_ISO;
         values[CallLogQuery.CACHED_NAME] = TEST_NAME;
         values[CallLogQuery.CACHED_NUMBER_TYPE] = TEST_NUMBER_TYPE;
         values[CallLogQuery.CACHED_NUMBER_LABEL] = TEST_NUMBER_LABEL;
         return values;
     }
 
-    /**
-     * Subclass of {@link CallLogAdapter} used in tests to intercept certain calls.
-     */
+    // Asserts that the name text view is shown and contains the given text./
+    private void assertNameIs(CallLogListItemViewHolder viewHolder, String name) {
+        assertEquals(View.VISIBLE, viewHolder.phoneCallDetailsViews.nameView.getVisibility());
+        assertEquals(name, viewHolder.phoneCallDetailsViews.nameView.getText());
+    }
+
+    /// Subclass of {@link CallLogAdapter} used in tests to intercept certain calls.
     private static final class TestCallLogAdapter extends CallLogAdapter {
         public TestCallLogAdapter(Context context, CallFetcher callFetcher,
                 ContactInfoHelper contactInfoHelper) {
diff --git a/tests/src/com/android/dialer/calllog/CallLogFragmentTest.java b/tests/src/com/android/dialer/calllog/CallLogFragmentTest.java
index 6f4b68b..aa4ad80 100644
--- a/tests/src/com/android/dialer/calllog/CallLogFragmentTest.java
+++ b/tests/src/com/android/dialer/calllog/CallLogFragmentTest.java
@@ -19,7 +19,6 @@
 import android.app.FragmentManager;
 import android.app.FragmentTransaction;
 import android.content.ComponentName;
-import android.content.ContentUris;
 import android.content.Context;
 import android.content.Intent;
 import android.content.res.Resources;
@@ -171,46 +170,6 @@
     }
 
     @MediumTest
-    public void testCallAndGroupviewHolder_GroupView() {
-        mCursor.moveToFirst();
-        insertPrivate(NOW, 0);
-        insertPrivate(NOW, 0);
-        insertPrivate(NOW, 0);
-        CallLogListItemViewHolder viewHolder = (CallLogListItemViewHolder)
-                mAdapter.onCreateViewHolder(mParentView, /* viewType */ 0);
-        mAdapter.onBindViewHolder(viewHolder, /* position */ 0);
-    }
-
-    @MediumTest
-    public void testCallAndGroupviewHolder_StandAloneView() {
-        mCursor.moveToFirst();
-        insertPrivate(NOW, 0);
-        CallLogListItemViewHolder viewHolder = (CallLogListItemViewHolder)
-                mAdapter.onCreateViewHolder(mParentView, /* viewType */ 0);
-        bindViewForTest(viewHolder);
-    }
-
-    @MediumTest
-    public void testCallAndGroupviewHolder_ChildView() {
-        mCursor.moveToFirst();
-        insertPrivate(NOW, 0);
-        CallLogListItemViewHolder viewHolder = (CallLogListItemViewHolder)
-                mAdapter.onCreateViewHolder(mParentView, /* viewType */ 0);
-        mAdapter.onBindViewHolder(viewHolder, /* position */ 0);
-    }
-
-    @MediumTest
-    public void testBindView_NumberOnlyNoCache() {
-        mCursor.moveToFirst();
-        insert(TEST_NUMBER, Calls.PRESENTATION_ALLOWED, NOW, 0, Calls.INCOMING_TYPE);
-        CallLogListItemViewHolder viewHolder = (CallLogListItemViewHolder)
-                mAdapter.onCreateViewHolder(mParentView, /* viewType */ 0);
-        bindViewForTest(viewHolder);
-
-        assertNameIs(viewHolder, TEST_NUMBER);
-    }
-
-    @MediumTest
     public void testBindView_NumberOnlyDbCachedFormattedNumber() {
         mCursor.moveToFirst();
         Object[] values = getValuesToInsert(TEST_NUMBER,
@@ -290,61 +249,6 @@
         assertLabel(viewHolder, TEST_FORMATTED_NUMBER, numberLabel);
     }
 
-    @MediumTest
-    public void testBindView_WithQuickContactBadge() {
-        mCursor.moveToFirst();
-        insertWithCachedValues(TEST_NUMBER, NOW, 0, Calls.INCOMING_TYPE,
-                "John Doe", Phone.TYPE_HOME, "");
-        CallLogListItemViewHolder viewHolder = (CallLogListItemViewHolder)
-                mAdapter.onCreateViewHolder(mParentView, /* viewType */ 0);
-        bindViewForTest(viewHolder);
-
-        assertTrue(viewHolder.quickContactView.isEnabled());
-    }
-
-    @MediumTest
-    public void testBindView_WithoutQuickContactBadge() {
-        mCursor.moveToFirst();
-        insert(TEST_NUMBER, Calls.PRESENTATION_ALLOWED, NOW, 0, Calls.INCOMING_TYPE);
-        CallLogListItemViewHolder viewHolder = (CallLogListItemViewHolder)
-                mAdapter.onCreateViewHolder(mParentView, /* viewType */ 0);
-        bindViewForTest(viewHolder);
-
-        assertFalse(viewHolder.quickContactView.isEnabled());
-    }
-
-    @MediumTest
-    public void testBindView_CallButton() {
-        mCursor.moveToFirst();
-        insert(TEST_NUMBER, Calls.PRESENTATION_ALLOWED, NOW, 0, Calls.INCOMING_TYPE);
-        CallLogListItemViewHolder viewHolder = (CallLogListItemViewHolder)
-                mAdapter.onCreateViewHolder(mParentView, /* viewType */ 0);
-        bindViewForTest(viewHolder);
-
-        // The primaryActionView tag is set in the
-        // {@link com.android.dialer.calllog.CallLogAdapter#bindView} method.  If it is possible
-        // to place a call to the phone number, a call intent will have been created for the
-        // primaryActionView.
-        IntentProvider intentProvider =
-                (IntentProvider) viewHolder.primaryActionButtonView.getTag();
-        Intent intent = intentProvider.getIntent(mActivity);
-        // Starts a call.
-        assertEquals(TestConstants.CALL_INTENT_ACTION, intent.getAction());
-        // To the entry's number.
-        assertEquals(Uri.parse("tel:" + TEST_NUMBER), intent.getData());
-    }
-
-    @MediumTest
-    public void testBindView_VoicemailUri() {
-        mCursor.moveToFirst();
-        insertVoicemail(TEST_NUMBER, Calls.PRESENTATION_ALLOWED, NOW, 0);
-        CallLogListItemViewHolder viewHolder = (CallLogListItemViewHolder)
-                mAdapter.onCreateViewHolder(mParentView, /* viewType */ 0);
-        bindViewForTest(viewHolder);
-
-        assertEquals(Uri.parse(viewHolder.voicemailUri),
-                ContentUris.withAppendedId(VoicemailContract.Voicemails.CONTENT_URI, 1));
-    }
 
     /** Returns the label associated with a given phone type. */
     private CharSequence getTypeLabel(int phoneType) {
@@ -384,7 +288,6 @@
         }
     }
 
-
     //
     // HELPERS to setup the tests.
     //
@@ -555,22 +458,6 @@
     }
 
     /**
-     * Insert a new voicemail entry in the test DB.
-     * @param number The phone number.
-     * @param presentation Number representing display rules for "allowed",
-     *               "payphone", "restricted", or "unknown".
-     * @param date In millisec since epoch. Use NOW to use the current time.
-     * @param duration In seconds of the call. Use RAND_DURATION to pick a random one.
-     */
-    private void insertVoicemail(String number, int presentation, long date, int duration) {
-        Object[] values = getValuesToInsert(number, presentation, date, duration, Calls.VOICEMAIL_TYPE);
-        // Must have the same index as the row.
-        values[CallLogQuery.VOICEMAIL_URI] =
-                ContentUris.withAppendedId(VoicemailContract.Voicemails.CONTENT_URI, mIndex);
-        insertValues(values);
-    }
-
-    /**
      * Insert a new private call entry in the test DB.
      * @param date In millisec since epoch. Use NOW to use the current time.
      * @param duration In seconds of the call. Use RAND_DURATION to pick a random one.
diff --git a/tests/src/com/android/dialer/voicemail/VoicemailPlaybackTest.java b/tests/src/com/android/dialer/voicemail/VoicemailPlaybackTest.java
index b9c70d3..6c7cf77 100644
--- a/tests/src/com/android/dialer/voicemail/VoicemailPlaybackTest.java
+++ b/tests/src/com/android/dialer/voicemail/VoicemailPlaybackTest.java
@@ -143,8 +143,7 @@
         mFakeAsyncTaskExecutor.runTask(CHECK_FOR_CONTENT);
         getInstrumentation().waitForIdleSync();
 
-        // Force the speakerphone to false to start.
-        mPresenter.setSpeakerphoneOn(false);
+        // Check that the speakerphone is false to start.
         assertFalse(mPresenter.isSpeakerphoneOn());
 
         View speakerphoneButton = mLayout.findViewById(R.id.playback_speakerphone);