суббота, 30 марта 2013 г.

The problem with an external camera in Android using MediaStore.ACTION_IMAGE_CAPTURE

We start native Camera using this code (short variant):

Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, NUMBER);

Don't forget Manifest.xml

<activity
android:name=".YourActivity"
android:screenOrientation="portrait"
android:configChanges="orientation|keyboardHidden"
</activity>

In  OnActivityResult we save information got from our external Camera, but after this in some devices we have this issue:
OnActivityResult
OnResume
OnPause
OnDestroy - there we lose all information from Camera
OnCreate
OnResume


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
      super.onActivityResult(requestCode, resultCode, data);
      mObject.setImagePath(....); - for example
}

Solution in two steps:

Step 1: Add OnSaveInstanceState and onRestoreInstanceState to your Class.

YourObject mObject = new YourObject();


@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);
  if(mObject != null) savedInstanceState.putSerializable(KEY, mObject);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
  super.onRestoreInstanceState(savedInstanceState);
  YourObject obj = (YourObject) savedInstanceState.getSerializable(KEY);
  if(obj != null) mObject = obj;
}


Step 2: Add piece of code to the OnCreate method.


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

YourObject obj = null;
try {
obj = (CarsDbModel) savedInstanceState.getSerializable(KEY);
} catch(NullPointerException e) {

}
 
if(car != null) {
      mObject = car;
}


After this code we will have this queue:
OnResume
OnPause
OnSaveInstanceState
OnDestroy
OnCreate - restore Correct Object

onRestoreInstanceState

OnResume


1 комментарий:

  1. step 2 isn't necessary, since you already set your object onRestoredInstanceState. And there is a wrong variable name there, you first declare as "obj", but later you use "car" instead

    ОтветитьУдалить