问题
I have an intent to select an image from The Gallery and then use that to load an image into an ImageView item.
BUT the image doesn't rotate in the right way so I should use ExifInterface class and exif constructor wants the file's path as String not as URI.
And to convert URI into string I wrote this method:
private String getRealPathFromURI(Uri contentURI) {
String result;
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = getActivity().getContentResolver()
.query(contentURI, proj, null, null, null);
if (cursor == null) {
result = contentURI.getPath();
} else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
result = cursor.getString(idx);
cursor.close();
}
return null;
}
And here where the problems start ...
result variable always return null no matter what. and I've tried a lot of solutions found here in stackoverflow as follow:
- I tried to query with null value for projection .. still return null and idx value is -1.
- I tried once with MediaStore.Images.Media.DATA and other time with MediaStore.Images.ImageColumns.DATA .. still return null
- I tried to get every column returns from the cursor one by one with projection been null .. not any of the values work with Exif.
- in the code above idx return 0 , so i check the column type via curser.getType(idx) and it returns 0 which means that this column is a null value.
- I made sure of permission to read from external storage .. still null
- I took the pen next to me and throw it really hard and it hit my cat .. still null and now my cat is mad at me.
So why all of that doesn't work? and what should i do?
回答1:
exif constructor wants the file's path as String not as URI.
Use android.support.media.ExifInterface
. It has a constructor that takes an InputStream. You get the InputStream
by calling getContentResolver().openInputStream(uri)
on some Context
(e.g., your Activity
), where uri
is your Uri
.
So why all of that doesn't work?
Because that code makes a lot of unfounded assumptions about the Uri
. There is no requirement for a Uri
to refer to a file on the filesystem that you can access, and there is no requirement that your query()
supports a DATA
column.
来源:https://stackoverflow.com/questions/52792939/android-get-filename-and-path-of-uri-from-mediastore