Get filename and path from URI from mediastore


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:


Or to a path gives:


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.

11/25/2016 9:48:55 AM

Accepted Answer

Below API 19 use this code to get File Path from URI:

public String getRealPathFromURI(Context context, Uri contentUri) {
  Cursor cursor = null;
  try { 
    String[] proj = { MediaStore.Images.Media.DATA };
    cursor = context.getContentResolver().query(contentUri,  proj, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    return cursor.getString(column_index);
  } finally {
    if (cursor != null) {
7/9/2018 6:20:19 PM

Just a simple update on the first answer: mActivity.managedQuery() is now deprecated. I've updated the code with the new method.

private String getRealPathFromURI(Uri contentUri) {
    String[] proj = { MediaStore.Images.Media.DATA };
    CursorLoader loader = new CursorLoader(mContext, contentUri, proj, null, null, null);
    Cursor cursor = loader.loadInBackground();
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    String result = cursor.getString(column_index);
    return result;

android dev source

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow