Path from URI returning Null when selecting from Photos or Gallery in Android – Solved

By | January 10, 2018

For API above 19

@SuppressLint("NewApi")
public static String getPathAPI19(Context context, Uri uri) {
    String filePath = "";
    String fileId = DocumentsContract.getDocumentId(uri);
    // Split at colon, use second item in the array
    String id = fileId.split(":")[1];
    String[] column = {MediaStore.Images.Media.DATA};
    String selector = MediaStore.Images.Media._ID + "=?";
    Cursor cursor = context.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            column, selector, new String[]{id}, null);
    int columnIndex = cursor.getColumnIndex(column[0]);
    if (cursor.moveToFirst()) {
        filePath = cursor.getString(columnIndex);
    }
    cursor.close();
    return filePath;
}

For API from 11 to 18

@SuppressLint("NewApi")
public static String getPathAPI11To18(Context context, Uri contentUri) {

    String[] proj = {MediaStore.Images.Media.DATA};
    String result = null;

    CursorLoader cursorLoader = new CursorLoader(
            context,
            contentUri, proj, null, null, null);
    Cursor cursor = cursorLoader.loadInBackground();

    if (cursor != null) {
        int column_index =
                cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        result = cursor.getString(column_index);
    }
    return result;

}

For API below 11

public static String getPathBelowAPI11(Context context, Uri contentUri) {

	String[] proj = {MediaStore.Images.Media.DATA};
	Cursor cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
	int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	cursor.moveToFirst();
	return cursor.getString(columnIndex);

}

Check this post to show the image selected from gallery in an imageview.

5 thoughts on “Path from URI returning Null when selecting from Photos or Gallery in Android – Solved

  1. Pingback: Select an Image from gallery in ANDROID and show it in an ImageView. – CoderzHeaven

  2. Cihan

    Thank you very much. I searched everywhere and finally saw your code and it works :)).

    Reply
  3. Asiri

    This works like a charm !!! Tested on Android API level 30 in 2022.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *