Android Camera OnActivityResult将照片路径重置为null

时间:2015-09-22 16:45:29

标签: android nullpointerexception android-camera uri onactivityresult

我在朋友Galaxy S4(GT i9505,Android 5.1)上测试我的应用时遇到了问题。为摄像机意图提供文件URI时,OnActivityResult会提供结果Activity.RESULT_OK,路径为null。它正在测试我测试的大多数其他设备(LG G3,nexus 5 ......)。这是我的代码:

GetOutputMediaFile

public File getOutputMediaFile(int type){
    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), MediaChooserConstants.folderName);
    if (! mediaStorageDir.exists()){
        if (! mediaStorageDir.mkdirs()){
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File mediaFile;
    if (type == MediaChooserConstants.MEDIA_TYPE_IMAGE){
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
    } else if(type == MediaChooserConstants.MEDIA_TYPE_VIDEO) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "VID_" + timeStamp + ".mp4");
    } else {
        return null;
    }
    return mediaFile;
}

OnActivityResult

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK) {
        String picturePath = null;
        if (requestCode == MediaChooserConstants.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
            picturePath = fileUri.getPath(); // <--- fileURI is null
        }
    }
}

DispatchTakePhotoIntent

private void dispatchTakePictureIntent() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File file = Utils.getInstance().getOutputMediaFile(MediaChooserConstants.MEDIA_TYPE_IMAGE);

    fileUri = Uri.fromFile(file); // create a file to save the image
    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file name

    //fileUri is not null here while debugging (../DCIM/.../IMG_XXX.jpg)
    startActivityForResult(intent, MediaChooserConstants.CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

}

2 个答案:

答案 0 :(得分:2)

您需要将文件路径保存到onSaveInstanceState中的捆绑包中,然后再从onRestoreInstanceState中再次从捆绑包中获取

答案 1 :(得分:2)

保存图像路径:

@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {

    if(mImageCaptureUri!=null)
        savedInstanceState.putString("camera_image", mImageCaptureUri.toString());

    super.onSaveInstanceState(savedInstanceState);
}

从中检索图像路径:

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {

    if (savedInstanceState != null) {
        if (savedInstanceState.containsKey("camera_image")) {
            mImageCaptureUri = Uri.parse(savedInstanceState.getString("camera_image"));
        }
    }

    super.onRestoreInstanceState(savedInstanceState);
}

发生此问题时,仅当用户转到相机意图时,并且当他捕获图像时,托管相机意图的活动在用户从相机意图返回时被破坏或重新创建。