4

I'm using this code to get the real path from a URI. It's working in marshmallow but not in Oreo:

private String getPathNew(Activity activity, Uri uri) { 
    if (isDownloadsDocument(uri)) {
        final String id = DocumentsContract.getDocumentId(uri);
        final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
        return getDataColumn(activity, contentUri, null, null);
    }
    return null;
}

public static String getDataColumn(Context context, Uri uri, String 
selection, String[] selectionArgs) {
    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {column};
    try {
        cursor = context.getContentResolver().query(uri, projection, selection, 
selectionArgs, null);
        if (cursor != null && cursor.moveToFirst()) {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}

What am I doing wrong?

Dan
  • 59,490
  • 13
  • 101
  • 110
Ravi Dhakad
  • 41
  • 1
  • 5
  • possible duplicate with https://stackoverflow.com/questions/13209494/how-to-get-the-full-file-path-from-uri – shizhen Oct 03 '18 at 07:30
  • @shizhen no it's not. this is a strange "bug" that only appeared in recent Android version, like Oreo. – Chen Li Yong Oct 12 '18 at 07:52
  • @ChenLiYong This error is caused due to a change in file policy introduced first in [Android 7.0](https://developer.android.com/about/versions/nougat/android-7.0-changes#permfilesys). The question what you are looking for is here https://stackoverflow.com/questions/43178911/android-7-nougat-how-to-get-the-file-path-from-uri-of-incoming-intent . – Kartik Ohri Jul 12 '19 at 11:24
  • @KartikOhri interesting to know. Thanks! – Chen Li Yong Jul 17 '19 at 04:19
  • 1
    This Solution worked fine with me: https://stackoverflow.com/questions/52775398/how-to-get-file-path-from-uri-in-android-oreo-8-1-or-above – Kareem Alsaifi Apr 28 '20 at 07:45

1 Answers1

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