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.

One thought 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

Leave a Reply

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