Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android data.getData() returns null from CameraActivity for some phones

Tags:

android

uri

null

I have a fatal error occurring in my onActivityResult coming back from a camera activity. What has me scratching my head is that the error is only happening on a handful of phones (based on the number of affected users) while there seems to be nothing wrong for the majority. I can duplicate the error on my Nexus 6 (running Lollipop 5.1.1) while my Note 5 (also 5.1.1) has no problems at all.

The problem is when I am trying to assign the imageUri from data.getData(). Debugging on the Note 5, data.mData equals "content://media/external/images/media/2215" while on the Nexus 6, data.mData is null.

I know this is a common question asked on SO but I haven't found anything that has helped me so far. Can anyone point me to the solution for this and provide an answer?

Method Starting Camera Activity for Result

@OnClick(R.id.change_image_camera) public void takePicture(){
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);}

onActvityResult

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == Activity.RESULT_OK) {

        Uri imageUri = data.getData(); //The trouble is here

        String realPath = Image.getPath(this, imageUri); //getPath crashes because imageUri is null

        Image.compressImage(realPath);

        File file = new File(realPath);

        Bundle extra = new Bundle();
        extra.putString("URL", realPath);
        returnIntent.putExtras(extra);

        setResult(RESULT_OK, returnIntent);
        finish();
    }
}

I greatly appreciate any help on this one!

like image 304
John Riggs Avatar asked Sep 04 '15 17:09

John Riggs


1 Answers

Uri imageUri = data.getData(); //The trouble is here

There is no requirement for a camera app to return a Uri pointing to the photo, as that is not part of the ACTION_IMAGE_CAPTURE Intent protocol. Either:

  • Supply EXTRA_OUTPUT in your ACTION_IMAGE_CAPTURE Intent, in which case you know where the image should be stored, and do not need to rely upon getData(), or

  • Use the data extra in the response Intent, which will be a Bitmap of a thumbnail of the image

Your next bug is here:

String realPath = Image.getPath(this, imageUri);

There is no requirement that the image be stored as a file that you can access, unless you provide a path to that location via EXTRA_OUTPUT.

like image 179
CommonsWare Avatar answered Nov 01 '22 06:11

CommonsWare