android get real path by Uri.getPath()
Is it really necessary for you to get a physical path?
For example, ImageView.setImageURI()
and ContentResolver.openInputStream()
allow you to access the contents of a file without knowing its real path.
This is what I do:
Uri selectedImageURI = data.getData();
imageFile = new File(getRealPathFromURI(selectedImageURI));
and:
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;
}
NOTE: managedQuery()
method is deprecated, so I am not using it.
Last edit: Improvement. We should close cursor!!