Skip to content

Instantly share code, notes, and snippets.

@WrathChaos
Last active March 29, 2021 10:46
Show Gist options
  • Save WrathChaos/0ac1e8c86ab737752bec8401d7776414 to your computer and use it in GitHub Desktop.
Save WrathChaos/0ac1e8c86ab737752bec8401d7776414 to your computer and use it in GitHub Desktop.
private 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);
       cursor.moveToFirst();
       return cursor.getString(column_index);
   } catch (Exception e) {
       Log.e(TAG, "getRealPathFromURI Exception : " + e.toString());
       return "";
   } finally {
       if (cursor != null) {
           cursor.close();
       }
   }
}
@abbasnaqdi
Copy link

Kotlin :

fun Uri.getPathString(context: Context): String {
    var path: String = ""

    context.contentResolver.query(
        this, arrayOf(MediaStore.Images.Media.DATA),
        null, null, null
    )?.apply {
        val columnIndex = getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
        moveToFirst()
        path = getString(columnIndex)
        close()
    }

    return path
}

@zunjae
Copy link

zunjae commented Nov 19, 2019

  1. It's unreliable across multiple Android devices

  2. no longer works on Android 10

@WrathChaos
Copy link
Author

Thank you @zunjae, It's been awhile working on Native Android. I'm going to revise it.

@zunjae
Copy link

zunjae commented Nov 19, 2019

I think an entirely new solution is required since the MediaStore.Images.Media.DATA field is deprecated

@WrathChaos
Copy link
Author

I think an entirely new solution is required since the MediaStore.Images.Media.DATA field is deprecated

I'm gonna working on it ASAP :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment