0

Trying to get real path from uri for a selected image, but I got a null for filePath = cursor.getString() while the cursor was not null at all.

Why?

In my app code, I have an onActivityResult returning from an mediastore image selection which I can get an URI for an image using the following:

Uri selectedImage = data.getData();

Then I try to get the real path of the selected image by calling the function as seen below.

realPath = RealPathUtil.getRealPathFromURI(this, selectedImage);

public static String getRealPathFromURI(Context context, Uri uri){

        String filePath = "";
        String[] column = { MediaStore.Images.Media.DATA };

        Cursor cursor = context.getContentResolver().query(uri,
                column, null, null, null);

        if( null != cursor ) {
            if (cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndex(column[0]);
                if( columnIndex > -1 )
                    filePath = cursor.getString(columnIndex); //why got a null
            }
            cursor.close();

        return filePath;
    }

The step-debugging environment is an AVD with API 23. I ran the app and selected a pic from internal storage\Pictures folder.

Just after running the row of code,

filePath = cursor.getString(columnIndex); 

I found filePath was null while then cursor.getCount() == 1 and columnIndex == 0.

Why is this?

Johnson
  • 157
  • 3
  • 17
  • 1
    First command: You should not try to get a 'real path' from an uri. – greenapps Jul 15 '18 at 09:27
  • I do not know what a "mediastore image selection" means in programming terms. In general, there is no file path for a `Uri`. See https://stackoverflow.com/q/49221312/115145 and https://stackoverflow.com/q/48510584/115145, for example. – CommonsWare Jul 15 '18 at 10:52
  • Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("image/*"); startActivityForResult(intent, 0); – Johnson Jul 16 '18 at 07:48
  • In my case, users browse and select an image from phone storage. I want to get where the selected file is. In fact, I have gotten it in the cursor as the cursor.getCount() == 1. But I am not clear why the cursor.getString() return null. Thank you all. – Johnson Jul 16 '18 at 07:57

0 Answers0