Emergency Info user name preference design change

- User name preference now will launch dialog same as change user name &
icon in Multiple users.
- Add permission for edit user name.
- Change robolectric properties sdk to 23 for fixing robolectric initialize
objects bug.

Test: make RunEmergencyInfoRoboTests

Bug: 112168722
Bug: 111967295
Bug: 116770817

Change-Id: I938983eaa0d21442ade59dde0f3f74eec3a62d22
Merged-In: I938983eaa0d21442ade59dde0f3f74eec3a62d22
diff --git a/AndroidManifest.xml b/AndroidManifest.xml
index 74daafe..e5ce533 100644
--- a/AndroidManifest.xml
+++ b/AndroidManifest.xml
@@ -21,6 +21,7 @@
     <uses-permission android:name="android.permission.CALL_PRIVILEGED" />
     <uses-permission android:name="android.permission.READ_CONTACTS" />
     <uses-permission android:name="android.permission.MANAGE_USERS" />
+    <uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL" />
 
     <application
         android:defaultToDeviceProtectedStorage="true"
@@ -98,6 +99,16 @@
             </intent-filter>
         </provider>
 
+        <provider
+            android:name="android.support.v4.content.FileProvider"
+            android:authorities="com.android.emergency.files"
+            android:grantUriPermissions="true"
+            android:exported="false">
+            <meta-data
+                android:name="android.support.FILE_PROVIDER_PATHS"
+                android:resource="@xml/file_paths" />
+        </provider>
+
     </application>
 
 </manifest>
diff --git a/res/layout/edit_user_info_dialog_content.xml b/res/layout/edit_user_info_dialog_content.xml
new file mode 100644
index 0000000..4d76e13
--- /dev/null
+++ b/res/layout/edit_user_info_dialog_content.xml
@@ -0,0 +1,49 @@
+<!--
+     Copyright (C) 2013 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.
+-->
+<LinearLayout
+    xmlns:android="http://schemas.android.com/apk/res/android"
+    android:layout_width="wrap_content"
+    android:layout_height="wrap_content"
+    android:baselineAligned="false"
+    android:padding="16dip">
+
+    <ImageView
+        android:id="@+id/user_photo"
+        android:layout_width="56dip"
+        android:layout_height="56dip"
+        android:layout_gravity="bottom"
+        android:layout_marginEnd="6dp"
+        android:contentDescription="@string/user_image_photo_selector"
+        android:background="@*android:drawable/spinner_background_holo_dark"
+        android:scaleType="fitCenter"/>
+
+    <EditText
+        android:id="@+id/user_name"
+        android:layout_width="0dip"
+        android:layout_height="wrap_content"
+        android:layout_gravity="bottom"
+        android:layout_weight="1"
+        android:layout_marginStart="6dp"
+        android:ellipsize="end"
+        android:singleLine="true"
+        android:textAppearance="?android:attr/textAppearanceMedium"
+        android:textAlignment="viewStart"
+        android:labelFor="@id/user_photo"
+        android:inputType="text|textCapWords"
+        android:selectAllOnFocus="true"
+        android:hint="@string/user_nickname"/>
+
+</LinearLayout>
diff --git a/res/values/strings.xml b/res/values/strings.xml
index 3db5ee1..76358fc 100644
--- a/res/values/strings.xml
+++ b/res/values/strings.xml
@@ -222,4 +222,8 @@
     <string name="user_image_take_photo">Take photo</string>
     <!-- An option in a photo selection dialog, if there is no photo yet [CHAR LIMIT=50] -->
     <string name="user_image_choose_photo">Choose photo from Gallery</string>
+    <!-- Accessibility message for the photo selector which is a button/popup with the current photo [CHAR LIMIT=50] -->
+    <string name="user_image_photo_selector">Select photo</string>
+    <!-- Title for the preference to enter the nickname of the user to display in the user switcher [CHAR LIMIT=25]-->
+    <string name="user_nickname">Nickname</string>
 </resources>
diff --git a/res/xml/edit_emergency_info.xml b/res/xml/edit_emergency_info.xml
index fdf6fec..2737b27 100644
--- a/res/xml/edit_emergency_info.xml
+++ b/res/xml/edit_emergency_info.xml
@@ -20,16 +20,11 @@
     <PreferenceCategory
             android:key="medical_info"
             android:title="@string/medical_info_title">
-        <com.android.emergency.preferences.NameAutoCompletePreference
-            android:enabled="false"
-            android:focusable="true"
+        <com.android.emergency.preferences.EmergencyNamePreference
             android:icon="@drawable/ic_account_circle_filled_24dp"
-            android:inputType="textCapWords|textPersonName"
             android:key="name"
-            android:selectable="false"
-            android:shouldDisableView="false"
-            android:singleLine="true"
-            android:title="@string/name" />
+            android:title="@string/name"
+            android:summary="@string/unknown_name" />
 
         <com.android.emergency.preferences.EmergencyEditTextPreference
             android:icon="@drawable/ic_home_24dp"
diff --git a/res/xml/edit_medical_info.xml b/res/xml/edit_medical_info.xml
index 0087f8a..1e572c7 100644
--- a/res/xml/edit_medical_info.xml
+++ b/res/xml/edit_medical_info.xml
@@ -18,14 +18,11 @@
     xmlns:app="http://schemas.android.com/apk/res-auto"
     android:key="edit_medical_info_settings">
 
-    <com.android.emergency.preferences.NameAutoCompletePreference
+    <com.android.emergency.preferences.EmergencyNamePreference
         android:icon="@drawable/ic_account_circle_filled_24dp"
-        android:inputType="textCapWords|textPersonName"
         android:key="name"
-        android:singleLine="true"
         android:title="@string/name"
-        app:summary="@string/unknown_name"
-        style="@style/NameAutoCompletePreference" />
+        app:summary="@string/unknown_name" />
 
     <com.android.emergency.preferences.EmergencyEditTextPreference
         android:icon="@drawable/ic_home_24dp"
diff --git a/res/xml/file_paths.xml b/res/xml/file_paths.xml
new file mode 100644
index 0000000..d0738ee
--- /dev/null
+++ b/res/xml/file_paths.xml
@@ -0,0 +1,20 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!-- Copyright (C) 2018 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.
+-->
+
+<paths xmlns:android="http://schemas.android.com/apk/res/android">
+    <!-- Offer access to files under Context.getCacheDir() -->
+    <cache-path name="my_cache" />
+</paths>
diff --git a/src/com/android/emergency/PreferenceKeys.java b/src/com/android/emergency/PreferenceKeys.java
index 89db2a6..bdfd47d 100644
--- a/src/com/android/emergency/PreferenceKeys.java
+++ b/src/com/android/emergency/PreferenceKeys.java
@@ -32,7 +32,7 @@
     /** Key for the add emergency contact preference */
     public static final String KEY_ADD_EMERGENCY_CONTACT = "add_emergency_contact";
 
-    /** Key to store and read the name of the user. */
+    /** Key for emergency name preference */
     public static final String KEY_NAME = "name";
 
     /** Key to store and read the address of the user. */
@@ -58,7 +58,7 @@
      *
      * <p>Note: Do not change the order of these keys, since the order is used to collect TRON stats
      */
-    public static final String[] KEYS_EDIT_EMERGENCY_INFO = {KEY_NAME, KEY_ADDRESS,
+    public static final String[] KEYS_EDIT_EMERGENCY_INFO = {KEY_ADDRESS,
             KEY_BLOOD_TYPE, KEY_ALLERGIES, KEY_MEDICATIONS,
             KEY_MEDICAL_CONDITIONS, KEY_ORGAN_DONOR};
 
diff --git a/src/com/android/emergency/edit/EditInfoFragment.java b/src/com/android/emergency/edit/EditInfoFragment.java
index 80d50c2..8199b70 100644
--- a/src/com/android/emergency/edit/EditInfoFragment.java
+++ b/src/com/android/emergency/edit/EditInfoFragment.java
@@ -16,10 +16,10 @@
 package com.android.emergency.edit;
 
 import android.app.Activity;
+import android.app.DialogFragment;
 import android.content.ActivityNotFoundException;
 import android.content.Context;
 import android.content.Intent;
-import android.content.SharedPreferences;
 import android.net.Uri;
 import android.os.Bundle;
 import android.provider.ContactsContract;
@@ -27,7 +27,6 @@
 import android.support.v7.preference.Preference;
 import android.support.v7.preference.Preference.OnPreferenceChangeListener;
 import android.support.v7.preference.PreferenceGroup;
-import android.support.v7.preference.PreferenceManager;
 import android.util.Log;
 import android.widget.Toast;
 
@@ -35,8 +34,11 @@
 import com.android.emergency.R;
 import com.android.emergency.ReloadablePreferenceInterface;
 import com.android.emergency.preferences.EmergencyContactsPreference;
+import com.android.emergency.preferences.EmergencyNamePreference;
 import com.android.emergency.util.PreferenceUtils;
 import com.android.internal.annotations.VisibleForTesting;
+import com.android.settingslib.CustomDialogPreference;
+import com.android.settingslib.CustomEditTextPreference;
 
 import java.util.HashMap;
 import java.util.Map;
@@ -48,12 +50,16 @@
     /** Result code for contact picker */
     private static final int CONTACT_PICKER_RESULT = 1001;
 
+    private static final String DIALOG_PREFERENCE_TAG = "dialog_preference";
+
     private final Map<String, Preference> mMedicalInfoPreferences =
             new HashMap<String, Preference>();
 
     /** The category that holds the emergency contacts. */
     private EmergencyContactsPreference mEmergencyContactsPreferenceCategory;
 
+    private EmergencyNamePreference mEmergencyNamePreference;
+
     @Override
     public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
         setPreferencesFromResource(R.xml.edit_emergency_info, rootKey);
@@ -69,6 +75,9 @@
             }
         }
 
+        mEmergencyNamePreference = (EmergencyNamePreference) findPreference(
+                PreferenceKeys.KEY_NAME);
+
         // Fill in emergency contacts.
         mEmergencyContactsPreferenceCategory = (EmergencyContactsPreference)
                 findPreference(PreferenceKeys.KEY_EMERGENCY_CONTACTS);
@@ -101,6 +110,7 @@
     public void onResume() {
         super.onResume();
         reloadFromPreference();
+        mEmergencyNamePreference.reloadFromUserManager();
     }
 
     /** Reloads the contacts by reading the value from the shared preferences. */
@@ -120,6 +130,24 @@
     }
 
     @Override
+    public void onDisplayPreferenceDialog(Preference preference) {
+        DialogFragment fragment = null;
+        if (preference instanceof CustomEditTextPreference) {
+            fragment = CustomEditTextPreference.CustomPreferenceDialogFragment
+                    .newInstance(preference.getKey());
+        } else if (preference instanceof CustomDialogPreference) {
+            fragment = EmergencyNamePreference.EmergencyNamePreferenceDialogFragment
+                    .newInstance(preference.getKey());
+        }
+        if (fragment != null) {
+            fragment.setTargetFragment(this, 0);
+            fragment.show(getFragmentManager(), DIALOG_PREFERENCE_TAG);
+        } else {
+            super.onDisplayPreferenceDialog(preference);
+        }
+    }
+
+    @Override
     public void onActivityResult(int requestCode, int resultCode, Intent data) {
         if (requestCode == CONTACT_PICKER_RESULT && resultCode == Activity.RESULT_OK) {
             Uri phoneUri = data.getData();
diff --git a/src/com/android/emergency/edit/EditMedicalInfoFragment.java b/src/com/android/emergency/edit/EditMedicalInfoFragment.java
index 1b0e3a3..3412b44 100644
--- a/src/com/android/emergency/edit/EditMedicalInfoFragment.java
+++ b/src/com/android/emergency/edit/EditMedicalInfoFragment.java
@@ -25,16 +25,22 @@
 import com.android.emergency.PreferenceKeys;
 import com.android.emergency.R;
 import com.android.emergency.ReloadablePreferenceInterface;
-import com.android.emergency.preferences.AutoCompleteEditTextPreference;
+import com.android.emergency.preferences.EmergencyNamePreference;
 import com.android.emergency.util.PreferenceUtils;
 import com.android.internal.logging.MetricsLogger;
 import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
+import com.android.settingslib.CustomDialogPreference;
 import com.android.settingslib.CustomEditTextPreference;
 
 /**
  * Fragment that displays personal and medical information.
  */
 public class EditMedicalInfoFragment extends PreferenceFragment {
+
+    private EmergencyNamePreference mEmergencyNamePreference;
+
+    private static final String DIALOG_PREFERENCE_TAG = "dialog_preference";
+
     @Override
     public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
         setPreferencesFromResource(R.xml.edit_medical_info, rootKey);
@@ -67,12 +73,16 @@
                 }
             });
         }
+
+        mEmergencyNamePreference = (EmergencyNamePreference) findPreference(
+                PreferenceKeys.KEY_NAME);
     }
 
     @Override
     public void onResume() {
         super.onResume();
         reloadFromPreference();
+        mEmergencyNamePreference.reloadFromUserManager();
     }
 
     @Override
@@ -81,13 +91,13 @@
         if (preference instanceof CustomEditTextPreference) {
             fragment = CustomEditTextPreference.CustomPreferenceDialogFragment
                     .newInstance(preference.getKey());
-        } else if (preference instanceof AutoCompleteEditTextPreference) {
-            fragment = AutoCompleteEditTextPreference.AutoCompleteEditTextPreferenceDialogFragment
+        } else if (preference instanceof CustomDialogPreference) {
+            fragment = EmergencyNamePreference.EmergencyNamePreferenceDialogFragment
                     .newInstance(preference.getKey());
         }
         if (fragment != null) {
             fragment.setTargetFragment(this, 0);
-            fragment.show(getFragmentManager(), "dialog_preference");
+            fragment.show(getFragmentManager(), DIALOG_PREFERENCE_TAG);
         } else {
             super.onDisplayPreferenceDialog(preference);
         }
diff --git a/src/com/android/emergency/preferences/EmergencyNamePreference.java b/src/com/android/emergency/preferences/EmergencyNamePreference.java
new file mode 100644
index 0000000..5393a05
--- /dev/null
+++ b/src/com/android/emergency/preferences/EmergencyNamePreference.java
@@ -0,0 +1,279 @@
+/*
+ * Copyright (C) 2018 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.emergency.preferences;
+
+import android.app.AlertDialog;
+import android.app.Fragment;
+import android.content.Context;
+import android.content.DialogInterface;
+import android.content.Intent;
+import android.graphics.Bitmap;
+import android.graphics.drawable.Drawable;
+import android.os.AsyncTask;
+import android.os.Bundle;
+import android.os.UserHandle;
+import android.os.UserManager;
+import android.support.v7.preference.DialogPreference;
+import android.text.TextUtils;
+import android.util.AttributeSet;
+import android.view.View;
+import android.widget.EditText;
+import android.widget.ImageView;
+
+import com.android.emergency.CircleFramedDrawable;
+import com.android.emergency.R;
+import com.android.internal.annotations.VisibleForTesting;
+import com.android.internal.util.UserIcons;
+import com.android.settingslib.CustomDialogPreference;
+
+import java.io.File;
+
+/**
+ * Custom {@link DialogPreference} that allows us to editing the user name and photo.
+ */
+public class EmergencyNamePreference extends CustomDialogPreference {
+
+    private static final String KEY_AWAITING_RESULT = "awaiting_result";
+    private static final String KEY_SAVED_PHOTO = "pending_photo";
+
+    private UserManager mUserManager = getContext().getSystemService(UserManager.class);
+    private EditUserPhotoController mEditUserPhotoController;
+    private Fragment mFragment;
+    private Bitmap mSavedPhoto;
+    private EditText mUserNameView;
+    private ImageView mUserPhotoView;
+    private boolean mWaitingForActivityResult = false;
+
+    public EmergencyNamePreference(Context context, AttributeSet attrs,
+            int defStyleAttr, int defStyleRes) {
+        super(context, attrs, defStyleAttr, defStyleRes);
+        setSummary(mUserManager.getUserName());
+        setIcon(getCircularUserIcon());
+        setDialogLayoutResource(R.layout.edit_user_info_dialog_content);
+    }
+
+    public EmergencyNamePreference(Context context, AttributeSet attrs, int defStyleAttr) {
+        this(context, attrs, defStyleAttr, 0);
+    }
+
+    public EmergencyNamePreference(Context context, AttributeSet attrs) {
+        this(context, attrs, R.attr.dialogPreferenceStyle);
+    }
+
+    public EmergencyNamePreference(Context context) {
+        this(context, null);
+    }
+
+    /**
+     * Setup fragment for Dialog and EditUserPhotoController.
+     */
+    public void setFragment(Fragment fragment) {
+        mFragment = fragment;
+    }
+
+    /**
+     * Reload user name and photo form UserManager.
+     */
+    public void reloadFromUserManager() {
+        setSummary(mUserManager.getUserName());
+        setIcon(getCircularUserIcon());
+    }
+
+    /**
+     * Restore user photo when EditUserPhotoController had pending photo.
+     */
+    public void onRestoreInstanceState(Bundle icicle) {
+        String pendingPhoto = icicle.getString(KEY_SAVED_PHOTO);
+        if (pendingPhoto != null) {
+            mSavedPhoto = EditUserPhotoController.loadNewUserPhotoBitmap(new File(pendingPhoto));
+        }
+        mWaitingForActivityResult = icicle.getBoolean(KEY_AWAITING_RESULT, false);
+    }
+
+    /**
+     * Save a temp user photo when layout need to recreating but Dialog is showing.
+     */
+    public void onSaveInstanceState(Bundle outState) {
+        if (getDialog() != null && getDialog().isShowing()
+                && mEditUserPhotoController != null) {
+            // Bitmap cannot be stored into bundle because it may exceed parcel limit
+            // Store it in a temporary file instead
+            File file = mEditUserPhotoController.saveNewUserPhotoBitmap();
+            if (file != null) {
+                outState.putString(KEY_SAVED_PHOTO, file.getPath());
+            }
+        }
+        if (mWaitingForActivityResult) {
+            outState.putBoolean(KEY_AWAITING_RESULT, mWaitingForActivityResult);
+        }
+    }
+
+    /**
+     * Set mWaitingForActivityResult to true when EmergencyNamePreferenceDialogFragment
+     * startActivityForResult, means we are waiting the activity result.
+     */
+    public void startingActivityForResult() {
+        mWaitingForActivityResult = true;
+    }
+
+    /**
+     * Reset mWaitingForActivityResult and send the result code to EditUserPhotoController when
+     * EmergencyNamePreferenceDialogFragment onActivityResult.
+     */
+    public void onActivityResult(int requestCode, int resultCode, Intent data) {
+        mWaitingForActivityResult = false;
+
+        if (getDialog() != null) {
+            mEditUserPhotoController.onActivityResult(requestCode, resultCode, data);
+        }
+    }
+
+    @Override
+    protected void onBindDialogView(View view) {
+        super.onBindDialogView(view);
+
+        mUserNameView = view.findViewById(R.id.user_name);
+        mUserNameView.setText(mUserManager.getUserName());
+        mUserPhotoView = view.findViewById(R.id.user_photo);
+        Drawable drawable;
+        if (mSavedPhoto != null) {
+            drawable = CircleFramedDrawable.getInstance(getContext(), mSavedPhoto);
+        } else {
+            drawable = getCircularUserIcon();
+        }
+        mUserPhotoView.setImageDrawable(drawable);
+
+        mEditUserPhotoController = createEditUserPhotoController(mUserPhotoView,
+                getCircularUserIcon());
+    }
+
+    @Override
+    protected void onPrepareDialogBuilder(AlertDialog.Builder builder,
+            DialogInterface.OnClickListener listener) {
+        super.onPrepareDialogBuilder(builder, listener);
+        builder.setTitle(R.string.name)
+                .setCancelable(true)
+                .setPositiveButton(android.R.string.ok, listener)
+                .setNegativeButton(android.R.string.cancel, listener)
+                .create();
+    }
+
+    @Override
+    protected void onDialogClosed(boolean positiveResult) {
+        super.onDialogClosed(positiveResult);
+        if (positiveResult) {
+            // Update the name if changed.
+            CharSequence userName = mUserNameView.getText();
+            if (!TextUtils.isEmpty(userName)) {
+                if (mUserManager.getUserName() == null
+                        || !userName.toString().equals(mUserManager.getUserName())) {
+                    mUserManager.setUserName(UserHandle.myUserId(), userName.toString());
+                    setSummary(userName);
+                }
+            }
+            // Update the photo if changed.
+            Drawable drawable = mEditUserPhotoController.getNewUserPhotoDrawable();
+            Bitmap bitmap = mEditUserPhotoController.getNewUserPhotoBitmap();
+            if (drawable != null && bitmap != null
+                    && !drawable.equals(getCircularUserIcon())) {
+                new AsyncTask<Void, Void, Void>() {
+                    @Override
+                    protected Void doInBackground(Void... params) {
+                        mUserManager.setUserIcon(UserHandle.myUserId(),
+                                mEditUserPhotoController.getNewUserPhotoBitmap());
+                        return null;
+                    }
+                }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);
+                setIcon(drawable);
+            }
+            if (mFragment != null) {
+                mFragment.getActivity().removeDialog(1);
+            }
+        }
+        clear();
+    }
+
+    private void clear() {
+        mEditUserPhotoController.removeNewUserPhotoBitmapFile();
+        mSavedPhoto = null;
+    }
+
+    private Drawable getCircularUserIcon() {
+        Bitmap bitmapUserIcon = mUserManager.getUserIcon(UserHandle.myUserId());
+
+        if (bitmapUserIcon == null) {
+            // get default user icon.
+            final Drawable defaultUserIcon = UserIcons.getDefaultUserIcon(
+                    getContext().getResources(), UserHandle.myUserId(), false);
+            bitmapUserIcon = UserIcons.convertToBitmap(defaultUserIcon);
+        }
+        Drawable drawableUserIcon = new CircleFramedDrawable(bitmapUserIcon,
+                (int) getContext().getResources().getDimension(R.dimen.circle_avatar_size));
+
+        return drawableUserIcon;
+    }
+
+    @VisibleForTesting
+    EditUserPhotoController createEditUserPhotoController(ImageView userPhotoView,
+                Drawable drawable) {
+        return new EditUserPhotoController(mFragment, userPhotoView,
+                mSavedPhoto, drawable, mWaitingForActivityResult);
+    }
+
+    public static class EmergencyNamePreferenceDialogFragment extends
+            CustomPreferenceDialogFragment {
+
+        public static CustomDialogPreference.CustomPreferenceDialogFragment newInstance(
+                String key) {
+            final CustomDialogPreference.CustomPreferenceDialogFragment
+                    fragment = new EmergencyNamePreferenceDialogFragment();
+            final Bundle b = new Bundle(1 /* capacity */);
+            b.putString(ARG_KEY, key);
+            fragment.setArguments(b);
+            return fragment;
+        }
+
+        private EmergencyNamePreference getEmergencyNamePreference() {
+            return (EmergencyNamePreference) getPreference();
+        }
+
+        @Override
+        public void onCreate(Bundle icicle) {
+            super.onCreate(icicle);
+            getEmergencyNamePreference().setFragment(this);
+            if (icicle != null) {
+                getEmergencyNamePreference().onRestoreInstanceState(icicle);
+            }
+        }
+
+        @Override
+        public void onSaveInstanceState(Bundle outState) {
+            super.onSaveInstanceState(outState);
+            getEmergencyNamePreference().onSaveInstanceState(outState);
+        }
+
+        @Override
+        public void onActivityResult(int requestCode, int resultCode, Intent data) {
+            getEmergencyNamePreference().onActivityResult(requestCode, resultCode, data);
+        }
+
+        @Override
+        public void startActivityForResult(Intent intent, int requestCode) {
+            getEmergencyNamePreference().startingActivityForResult();
+            super.startActivityForResult(intent, requestCode);
+        }
+    }
+}
diff --git a/tests/robolectric/config/robolectric.properties b/tests/robolectric/config/robolectric.properties
index c727238..7865720 100644
--- a/tests/robolectric/config/robolectric.properties
+++ b/tests/robolectric/config/robolectric.properties
@@ -1,2 +1,2 @@
 manifest=packages/apps/EmergencyInfo/AndroidManifest.xml
-sdk=NEWEST_SDK
\ No newline at end of file
+sdk=23
\ No newline at end of file
diff --git a/tests/robolectric/src/com/android/emergency/edit/EditInfoFragmentTest.java b/tests/robolectric/src/com/android/emergency/edit/EditInfoFragmentTest.java
index d0f1a78..1c8e9dc 100644
--- a/tests/robolectric/src/com/android/emergency/edit/EditInfoFragmentTest.java
+++ b/tests/robolectric/src/com/android/emergency/edit/EditInfoFragmentTest.java
@@ -11,8 +11,8 @@
 import android.content.ComponentName;
 import android.content.Context;
 import android.content.pm.PackageManager;
-import androidx.preference.Preference;
-import androidx.preference.Preference.OnPreferenceChangeListener;
+import android.support.v7.preference.Preference;
+import android.support.v7.preference.Preference.OnPreferenceChangeListener;
 import com.android.emergency.edit.EditInfoFragment.PreferenceChangeListener;
 import org.junit.Before;
 import org.junit.Test;
diff --git a/tests/robolectric/src/com/android/emergency/preferences/EmergencyNamePreferenceTest.java b/tests/robolectric/src/com/android/emergency/preferences/EmergencyNamePreferenceTest.java
new file mode 100644
index 0000000..416b06f
--- /dev/null
+++ b/tests/robolectric/src/com/android/emergency/preferences/EmergencyNamePreferenceTest.java
@@ -0,0 +1,173 @@
+/*
+ * Copyright (C) 2018 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.emergency.preferences;
+
+import static com.google.common.truth.Truth.assertThat;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.same;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+import android.app.Dialog;
+import android.content.Context;
+import android.content.Intent;
+import android.graphics.Bitmap;
+import android.graphics.drawable.Drawable;
+import android.os.UserManager;
+import android.view.View;
+import android.view.ViewGroup;
+import android.widget.EditText;
+import android.widget.ImageView;
+import android.widget.LinearLayout;
+import android.widget.TextView;
+import com.android.emergency.R;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Answers;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+import org.robolectric.RobolectricTestRunner;
+import org.robolectric.RuntimeEnvironment;
+
+@RunWith(RobolectricTestRunner.class)
+public class EmergencyNamePreferenceTest {
+
+    private final Bitmap mBitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888);
+    @Mock
+    private UserManager mUserManager;
+    @Mock
+    private Dialog mDialog;
+    private Context mContext;
+    private EditText mNameView;
+    private ImageView mIconView;
+    private TestEmergencyNamePreference mTestEmergencyNamePreference;
+
+    @Before
+    public void setUp() {
+        MockitoAnnotations.initMocks(this);
+        mContext = spy(RuntimeEnvironment.application);
+        when(mContext.getSystemService(UserManager.class)).thenReturn(mUserManager);
+        when(mUserManager.getUserIcon(0)).thenReturn(mBitmap);
+
+        mTestEmergencyNamePreference = spy(new TestEmergencyNamePreference(mContext));
+    }
+
+    @Test
+    public void emergencyNamePreference_setDefaultProperties_defaultPropertiesIsSet() {
+        assertThat(mTestEmergencyNamePreference.isEnabled()).isTrue();
+        assertThat(mTestEmergencyNamePreference.isSelectable()).isTrue();
+    }
+
+
+    @Test
+    public void loadDataFromUserManager_setUserNameAndPhoto_preferenceSummaryAndIconIsSet() {
+        assertThat(mTestEmergencyNamePreference.getSummary()).isNull();
+        assertThat(mTestEmergencyNamePreference.getIcon()).isNull();
+
+        when(mUserManager.getUserName()).thenReturn("Wesley");
+        mTestEmergencyNamePreference.reloadFromUserManager();
+
+        assertThat(mTestEmergencyNamePreference.getSummary()).isEqualTo(mUserManager.getUserName());
+        assertThat(mTestEmergencyNamePreference.getIcon()).isNotNull();
+    }
+
+    @Test
+    public void onBindDialogView_setUserName_textViewTitleIsSet() {
+        View view = createLayout();
+        when(mUserManager.getUserName()).thenReturn("Wesley");
+
+        mTestEmergencyNamePreference.onBindDialogView(view);
+
+        TextView textView = view.findViewById(R.id.user_name);
+        assertThat(textView.getText().toString()).isEqualTo(mUserManager.getUserName());
+    }
+
+    @Test
+    public void onBindDialogView_setUserPhoto_imageViewDrawableIsSet() {
+        View view = createLayout();
+
+        mTestEmergencyNamePreference.onBindDialogView(view);
+
+        ImageView imageView = view.findViewById(R.id.user_photo);
+        assertThat(imageView.getDrawable()).isNotNull();
+    }
+
+    @Test
+    public void onBindDialogView_setEditUserPhotoController_editUserPhotoControllerIsSet() {
+        View view = createLayout();
+
+        EditUserPhotoController photoController = mTestEmergencyNamePreference.getPhotoController();
+        assertThat(photoController).isNull();
+
+        mTestEmergencyNamePreference.onBindDialogView(view);
+
+        photoController = mTestEmergencyNamePreference.getPhotoController();
+        assertThat(photoController).isNotNull();
+    }
+
+    @Test
+    public void onActivityResult_whenWaitingForActivityResult_onActivityResultIsCalled() {
+        View view = createLayout();
+
+        mTestEmergencyNamePreference.onBindDialogView(view);
+        doReturn(mDialog).when(mTestEmergencyNamePreference).getDialog();
+        mTestEmergencyNamePreference.startingActivityForResult();
+        Intent resultData = new Intent();
+        mTestEmergencyNamePreference.onActivityResult(0, 0, resultData);
+        EditUserPhotoController photoController = mTestEmergencyNamePreference.getPhotoController();
+        verify(photoController).onActivityResult(eq(0), eq(0), same(resultData));
+    }
+
+    private ViewGroup createLayout() {
+        ViewGroup root = new LinearLayout(mContext);
+
+        mNameView = new EditText(mContext);
+        mNameView.setId(R.id.user_name);
+        root.addView(mNameView);
+
+        mIconView = new ImageView(mContext);
+        mIconView.setId(R.id.user_photo);
+        root.addView(mIconView);
+
+        return root;
+    }
+
+    public class TestEmergencyNamePreference extends EmergencyNamePreference {
+
+        private EditUserPhotoController mPhotoController;
+
+        public TestEmergencyNamePreference(Context context) {
+            super(context, null);
+            setSummary(mUserManager.getUserName());
+            setIcon(null);
+        }
+
+        public EditUserPhotoController getPhotoController() {
+            return mPhotoController;
+        }
+
+        @Override
+        protected EditUserPhotoController createEditUserPhotoController(ImageView userPhotoView,
+            Drawable drawable) {
+            mPhotoController = mock(EditUserPhotoController.class, Answers.RETURNS_DEEP_STUBS);
+            return mPhotoController;
+        }
+    }
+}