Hung Nguyen Hung Nguyen - 1 year ago 483
Android Question

Android startActivityForResult returns null to onActivityResult when using camera

I am having a problem with startActivityForResult/onActivityResult where data returns null. I use startActivityForResult(camera) and manage to save the image into the device.

This is the piece in the activity that calls the Camera

protected void onCreate(Bundle savedInstanceState) {

imageButton.setOnClickListener(new MyCamera(this));

This is my onActivityResult function

protected void onActivityResult(int requestCode,int resultCode, Intent data){
Log.i("request, result Code", String.valueOf(requestCode) + " and " + String.valueOf(resultCode));
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK && data != null){
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap)extras.get("data");

This is where I call startActivityForResult and save the image to file.

Uri photoURI = FileProvider.getUriForFile(mContext,
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
mContext.startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);

This is the error message, it happens because 'Intent data' is null. I have tried to look at other posts which are similar but didn't manage to figure out the reason why.

java.lang.RuntimeException: Failure delivering result
ResultInfo{who=null, request=1, result=-1, data=null} to activity {autosoftpro.reusedtire/autosoftpro.reusedtire.UploadTireActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference

Answer Source

it happens because 'Intent data' is null

As is explained in the documentation for ACTION_IMAGE_CAPTURE, there are two possibilities:

  • You include EXTRA_OUTPUT in the ACTION_IMAGE_CAPTURE Intent. In that case, you are not returned anything in the Intent delivered to onActivityResult(), but you already know where the image should be.

  • You do not include EXTRA_OUTPUT, in which case the data extra will be a thumbnail `Bitmap.

You are including EXTRA_OUTPUT, which means you should not be checking the data extra. Instead, look for the image wherever you specified in EXTRA_OUTPUT.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download