Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GetRealPathFromUri always get null result

Tags:

android

uri

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();
        }
    }
}
like image 750
Chlebta Avatar asked Mar 04 '26 18:03

Chlebta


1 Answers

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.

like image 173
Budius Avatar answered Mar 08 '26 22:03

Budius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!