adalpari
adalpari

Reputation: 3121

Error getting image path selected by Gallery Intent (Android 6 - Some devices)

I am trying to get the path of an image when the user pick from the gallery (with intent)

It's been working ok, since some users noticed that could not do it witn Android 6.0.

I have tried different things, and some solutions works in the emulator with Android 6.0 but not in my Xiamoi with Android 6.1.

This both solutions works in the emulator (6.0) and Android 4.4 physycal device.

public String getRealPathFromURI(Activity context, Uri contentURI) {
    String[] projection = { MediaStore.Images.Media.DATA };
    @SuppressWarnings("deprecation")
    Cursor cursor = context.managedQuery(contentURI, projection, null,
            null, null);
    if (cursor == null)
        return null;
    int column_index = cursor
            .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    if (cursor.moveToFirst()) {
        String s = cursor.getString(column_index);
        // cursor.close();
        return s;
    }
    // cursor.close();
    return null;
}

and the other similar:

private static String getRealPathFromURI(Context context, Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] proj = {MediaStore.Images.Media.DATA};
        cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

But in my Xiaomi 6.1 the cursor is null. But I can get the real path from:

private static String getRealPathFromURI(Context context, Uri contentUri) {
    return contentUri.getEncodedPath();
}

Any help? Thank you!

EDIT:

I'm asking for choose an image in this way:

Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/*");
intent.setAction(Intent.ACTION_PICK); //ACTION_GET_CONTENT
// Always show the chooser (if there are multiple options available)
launchForResult(Intent.createChooser(intent, "Select Picture"), SELECT_FILE);

Upvotes: 0

Views: 575

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007099

I'm asking for choose an image in this way:

First, use ACTION_GET_CONTENT to pick by MIME type.

Second, whatever activity that responds to ACTION_GET_CONTENT (or ACTION_PICK) does not need to return a Uri that the MediaStore knows about. In fact, most will not. They can return a Uri that points to anything, including things that are not files.

So, get rid of all of your broken getRealPathFromURI() code. Use ContentResolver and openInputStream() to get an InputStream on the content identified by the Uri, and use that stream.

Upvotes: 1

Related Questions