Fix crash after rotating SIM import screen on LMP

Test
manually verify that no crash occurs when rotating SIM import screen
on LMP emulator

Bug 33108913

Change-Id: Idcee6fa98f4cefb83aed60bf9648d69748a0c83b
diff --git a/src/com/android/contacts/SimImportFragment.java b/src/com/android/contacts/SimImportFragment.java
index c8a9b9a..b512599 100644
--- a/src/com/android/contacts/SimImportFragment.java
+++ b/src/com/android/contacts/SimImportFragment.java
@@ -191,7 +191,7 @@
         int importableCount = 0;
         final SparseBooleanArray checked = mListView.getCheckedItemPositions();
         for (int i = 0; i < checked.size(); i++) {
-            if (checked.valueAt(i) && !mAdapter.existsInCurrentAccount(i)) {
+            if (checked.valueAt(i) && !mAdapter.existsInCurrentAccount(checked.keyAt(i))) {
                 importableCount++;
             }
         }
@@ -215,9 +215,11 @@
 
     @Override
     public void onSaveInstanceState(Bundle outState) {
+        rememberSelectionsForCurrentAccount();
+        // We'll restore this manually so we don't need the list to preserve it's own state.
+        mListView.clearChoices();
         super.onSaveInstanceState(outState);
         mAccountHeaderPresenter.onSaveInstanceState(outState);
-        rememberSelectionsForCurrentAccount();
         saveAdapterSelectedStates(outState);
     }
 
@@ -276,7 +278,7 @@
             // It's possible for existing contacts to be "checked" but we only want to import the
             // ones that don't already exist
             if (checked.valueAt(i) && !mAdapter.existsInCurrentAccount(i)) {
-                importableContacts.add(mAdapter.getItem(i));
+                importableContacts.add(mAdapter.getItem(checked.keyAt(i)));
             }
         }
         ContactSaveService.startService(getContext(), ContactSaveService
@@ -350,6 +352,11 @@
 
         @Override
         public long getItemId(int position) {
+            // This can be called by the framework when the adapter hasn't been initialized for
+            // checking the checked state of items. See b/33108913
+            if (position < 0 || position >= getCount()) {
+                return View.NO_ID;
+            }
             return getItem(position).getId();
         }