Created
April 10, 2017 02:24
-
-
Save hu2di/6a3be01bdd4eb6b39508e03c9cc1e9d6 to your computer and use it in GitHub Desktop.
Android: Get Real Path From URI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} | |
} |
not working
not working
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
Do you have any idea how to write this as an extension function in Kotlin? I tried this:
But I'm getting
java.lang.IllegalStateException: cursor.getString(columnIndex) must not be null