Android data.getData() returns null from CameraAct

2019-02-17 16:03发布

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!

标签: android null uri
1条回答
看我几分像从前
2楼-- · 2019-02-17 16:08
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.

查看更多
登录 后发表回答