GetRealPathFromUri always get null result

2020-02-14 07:45发布

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();
        }
    }
}

标签: android uri
1条回答
趁早两清
2楼-- · 2020-02-14 08:29

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.

查看更多
登录 后发表回答