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.
Pingback: Select an Image from gallery in ANDROID and show it in an ImageView. – CoderzHeaven
Thank you very much. I searched everywhere and finally saw your code and it works :)).
I am glad to hear that my code worked for you.
This works like a charm !!! Tested on Android API level 30 in 2022.
Thanks alot.your solution helped me alot