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

时光总嘲笑我的痴心妄想 提交于 2019-12-18 06:13:48

问题


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!


回答1:


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.



来源:https://stackoverflow.com/questions/32403265/android-data-getdata-returns-null-from-cameraactivity-for-some-phones

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!