Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
954 views
in Technique[技术] by (71.8m points)

android - GetRealPathFromUri always get null result

I'm trying to get real path from Uri(Of selected image from gallery) but This function returns always null value :

//Convert the image URI to the direct file system path of the image file
public String getRealPathFromURI(Uri contentUri) {

    Cursor cursor = null;
    try {

        String[] proj = { MediaStore.Images.Media.DATA };
        cursor = getActivity().getContentResolver().query(contentUri,  proj, null, null, null);
        cursor.moveToFirst();
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        return cursor.getString(column_index);
    } finally {

        if (cursor != null) {

            cursor.close();
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That's because the image you're selecting is not physically available on the device.

Images from gallery or other choose can come from different sources that does not provide a physical file, like a cloud storage for example.

Check this code here on how to open the Uri as a InputStream that can be used to create a copy of the file (or just read directly).

Android: Getting a file URI from a content URI?

edit:

I'm doing some extra research on it, apparently it also varies on how you request this Uri.

if you request it like this (which is the current preferred method as per Android guides):

 i = new Intent(Intent.ACTION_GET_CONTENT);
 i.addCategory(Intent.CATEGORY_OPENABLE);
 i.setType("image/*");
 startActivityForResult(i, REQUEST_STORAGE);

and it opens the KitKat style unified selector, if you choose an image from there, it will always return null. If you open the left-drawer menu, select the gallery (or a file browser), and pick an image from there, then, if it is a local file image, you will have the correct path.

on the other hand, if you request it like this (which is the old method):

 i = new Intent(Intent.ACTION_PICK);
 i.setType("image/*");
 startActivityForResult(i, REQUEST_STORAGE);

it will directly open the Gallery, and again, if it is a local file image, you will have the correct path.

So yeah, I still don't believe there's a way to force local only, but at least you have more information to make an informed decision on your coding.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...