Q: Get filename and path from uri from mediastore

D: I have an onActivityResult returning from an mediastore image selection which I can get a URI for an image using the following:
Uri selectedImage = data.getData();
Converting this to a string gives this:
content://media/external/images/media/47
Or to a path gives:
/external/images/media/47
However I can't seem to find a way to convert this into an absolute path, as I want to load the image into a bitmap without having to copy it somewhere. I know this can be done using the URI and content resolver but this seems to break on rebooting of the phone, I guess MediaStore doesn't keep its numbering the same between reboots.

Test Case #13


File ID: #3414749-0-cc


public static String getRealPathFromUri(final Context context, final Uri contentUri) {
    Cursor cursor = null;
    try {
        final String[] proj = {MediaStore.Images.Media.DATA};
        cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } finally {
        if (cursor ! = null) {
            cursor.close();
        }
    }
}

  1. Instead of managedQuery(.........) (deprecated) you can use getContentResolver().query(.....) with the same parameters. Nice work
  2. As Christopher points out - this is not supported in 4.4+ See this question for more info: http://stackoverflow.com/questions/20067508/get-real-path-from-uri-android-kitkat-new-storage-access-framework/20402190?noredirect=1#comment30507493_20402190
  3. In the newest Android version (KitKat) this gives an error: the path String is null.

Comments Quality
Accurate?:
Precise?:
Concise?:
Useful?: