Skip to content

Instantly share code, notes, and snippets.

@hu2di
Created April 10, 2017 02:24
Show Gist options
  • Save hu2di/6a3be01bdd4eb6b39508e03c9cc1e9d6 to your computer and use it in GitHub Desktop.
Save hu2di/6a3be01bdd4eb6b39508e03c9cc1e9d6 to your computer and use it in GitHub Desktop.
Android: Get Real Path From URI
public 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);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
@sachinrkeche
Copy link

cursor returns null .

@whereiskieran
Copy link

Try this

private String getRealPathFromURI(Uri contentURI) {
    String result;
    Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
    if (cursor == null) { // Source is Dropbox or other similar local file path
        result = contentURI.getPath();
    } else {
        cursor.moveToFirst();
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        result = cursor.getString(idx);
        cursor.close();
    }
    return result;
}

@micer
Copy link

micer commented Aug 2, 2018

Do you have any idea how to write this as an extension function in Kotlin? I tried this:

fun Uri.getRealPath(context: Context): String {
    var cursor: Cursor? = null
    try {
        val proj = arrayOf(MediaStore.Images.Media.DATA)
        cursor = context.contentResolver.query(this, proj, null, null, null)
        val columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
        cursor.moveToFirst()
        return cursor.getString(columnIndex)
    } catch (e: Exception) {
        Timber.e(e)
        return ""
    } finally {
        cursor?.close()
    }
}

But I'm getting java.lang.IllegalStateException: cursor.getString(columnIndex) must not be null

@androidovshchik
Copy link

not working

@xmatikag
Copy link

not working

@rakshitsoni02
Copy link

private fun getRealPathFromURI(context: Context, contentURI: Uri): String? {
val result: String?
val cursor: Cursor? = context.contentResolver.query(
contentURI, null, null, null, null
)
if (cursor == null) {
result = contentURI.path
} else {
cursor.moveToFirst()
val idx: Int = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
result = cursor.getString(idx)
cursor.close()
}
return result
}

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