Android – How to get Uri of image taken with camera and stored to Gallery

androidcameragallery

I'm launching camera from my application. I'm using Android.provider.MediaStore.ACTION_IMAGE_CAPTURE with extra android.provider.MediaStore.EXTRA_OUTPUT. If I use EXTRA_OUTPUT or not, photo is added to gallery.

How to get the Uri of the image in Gallery? I haven't found a clean way to do this, and I don't want to use the Uri of last added image to Gallery, because I can not be sure that it is the photo user took.

Edit:
Let me add here, that I do know how to get the image. Currently I'm using my Uri which I'm passing with Intent as an EXTRA_OUTPUT. That is not the problem. The problem is that using this method I get two photos written to sdcard, and I prefer that only one is written. Or in case of two is written, one in gallery and one in my own Uri, I would like to use one of those Uri:s and delete the other one. In both of the cases, I need the Uri of the photo, which is saved to Gallery by default.

Best Solution

If you start the camera by calling

startActivityForResult(cameraIntent, REQUEST_CODE_CAPTURE_IMAGE_ACTIVITY); // start the camera

in onActivityResult you can capture the mediaURI

 @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        if (requestCode == REQUEST_CODE_CAPTURE_IMAGE_ACTIVITY
                && resultCode == RESULT_OK) {
                Uri imageUri = null;
                if (data != null){
                   imageUri = data.getData();
               }
        }
    }

REQUEST_CODE_CAPTURE_IMAGE_ACTIVITY is a static integer value that's used to identify the request that was made through the intent. This is so if you have multiple startActivityForResults you can identify which one is coming back.

Note that if you pre-insert a URI through EXTRA_OUTPUT you will NOT get the URI back through data.getData(); You will have to store the pre-inserted URI in a variable and retrieve it in your onActivityResult while checking to see if imageUri is null..

Ex.

 Uri imageUri = null;
if (data != null){
   imageUri = data.getData();
}
if (imageUri == null && preinsertedUri != null)
 imageUri = preinsertedUri;

// do stuff with imageUri