Prevent camera app crashes on changing hw.camera.* settings

If the AVD's config.ini changes hw.camera.*, this is effectively,
connecting/disconnecting camera hardware, and the current
way in which camera settings are handled assumes
that the set of cameras never changes, which can lead to
the camera app crashing if the camera app was used successfuly
with one configuration of hw.camera.* and then
the AVD was restarted with a different configuration.

In particular, the crash happens if the number of cameras
has been reduced since the last run, and the camera app
is looking up a preferred camera ID that is not supported
by the new number of cameras.

bug: 28417929
BUG: https://code.google.com/p/android/issues/detail?id=206945

Change-Id: Ib0e26ae77d376f31f3cc281e386d3c67291c1edc
(cherry picked from commit 8f339abd9245577c348f5ba22322e8801c21faf8)
diff --git a/src/com/android/camera/Camera.java b/src/com/android/camera/Camera.java
index 2ca7944..b50ab18 100644
--- a/src/com/android/camera/Camera.java
+++ b/src/com/android/camera/Camera.java
@@ -1085,7 +1085,21 @@
     private void getPreferredCameraId() {
         mPreferences = new ComboPreferences(this);
         CameraSettings.upgradeGlobalPreferences(mPreferences.getGlobal());
-        mCameraId = CameraSettings.readPreferredCameraId(mPreferences);
+
+        mNumberOfCameras = CameraHolder.instance().getNumberOfCameras();
+        int attemptedCameraId = CameraSettings.readPreferredCameraId(mPreferences);
+
+        // It is possible that the user can connect/disconnect cameras
+        // between device boots.
+        // We need to check that the preferred camera ID
+        // does not refer to a disconnected camera.
+        if (attemptedCameraId >= mNumberOfCameras) {
+            Log.v(TAG, "Preferred camera (id= " + attemptedCameraId +
+                       ") missing. Defaulting to the first one");
+            mCameraId = 0;
+        } else {
+            mCameraId = attemptedCameraId;
+        }
 
         // Testing purpose. Launch a specific camera through the intent extras.
         int intentCameraId = Util.getCameraFacingIntentExtras(this);
@@ -1144,7 +1158,6 @@
         mPreferences.setLocalId(this, mCameraId);
         CameraSettings.upgradeLocalPreferences(mPreferences.getLocal());
 
-        mNumberOfCameras = CameraHolder.instance().getNumberOfCameras();
         mQuickCapture = getIntent().getBooleanExtra(EXTRA_QUICK_CAPTURE, false);
 
         // we need to reset exposure for the preview