I have a piece of code that aims to launch the android camera, let the user take a photo and eventually keep the uri of the image once it is saved.
So far I have managed to get it working. However, it seems like a 50/50 chance that the app will crash with a NPE. I have no idea why this is happening
my code:
private Uri mImageCaptureUri;
private void doTakePhotoAction() {
String fileName = "temp.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
mImageCaptureUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
startActivityForResult(intent, PICK_FROM_CAMERA);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != RESULT_OK) {
return;
}
switch (requestCode) {
case PICK_FROM_CAMERA:
String[] projection = { MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(mImageCaptureUri, projection, null, null, null);
int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String capturedImageFilePath = cursor.getString(column_index_data);
Intent intent = new Intent(this, CropImage.class);
intent.putExtra("image-path", capturedImageFilePath);
intent.putExtra("scale", true);
startActivity(intent);
break;
}
}
The NPE error refers me back to the line
Cursor cursor = managedQuery(mImageCaptureUri, projection, null, null, null);
and it is being thrown because mImageCaptureUri is null. Does anyone have any ideas on how to fix / work around this or why this is in fact happening
You really have to take to heart the first rule of Android Activities: Android may decide at any time to kill your activity, resetting all member variables in the process. It will simply rebuild the activity once it needs to handle
onActivityResult… but as you initializedmImageCaptureUriin your specific handler, it will now be null.The classic cause in your example would be an orientation change during the launched “capture an image” activity (orientation changes will typically kill the activity), but there is a myriad of other reasons why android would decide to terminate it (lack of memory, incoming calls, phone having a bad hair day, etc).
The solution is to store and restore state like
mImageCaptureUriinonSaveInstanceState(), and restore it in theonCreate()of the Activity, i.e.