Skip to content Skip to sidebar Skip to footer

Android 5.1.1 Lollipop Return Null File Path If Image Chosen From Gallery

Android 5.1.1 lollipop return null file path if image chosen from gallery. The below code works fine in all the devices below 5.1.1, but doesn't work in lollipop 5.1.1 Uri contentU

Solution 1:

For now I have ended up with this for getting an image from gallery. I've tested it on 4.4, 5.0.1 and 5.1.1 but it should work on previous versions too (with new and old Google photo app), should be less hacky and doesn't require a check on Android version.

public static Uri handleImageUri(Uri uri) {
    if (uri.getPath().contains("content")) {
        Pattern pattern = Pattern.compile("(content://media/.*\\d)");
        Matcher matcher = pattern.matcher(uri.getPath());
        if (matcher.find())
            return Uri.parse(matcher.group(1));
        else
            throw new IllegalArgumentException("Cannot handle this URI");
    }
    return uri;
}

And with this I used the same code I have ever used before for getting the image path:

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

Solution 2:

For a temporary hack-around for android lollipop 5.1.1. It Works fine now. But m not satisfied with this unofficial hack.

Uri selectedImage = data.getData();
        if (Build.VERSION.SDK_INT == 22) {
            if (selectedImage != null && selectedImage.toString().length() > 0) {
                try {
                    final String extractUriFrom = selectedImage.toString();
                    String firstExtraction = extractUriFrom.contains("com.google.android.apps.photos.contentprovider") ? extractUriFrom.split("/1/")[1] : extractUriFrom;
                    firstExtraction = firstExtraction.contains("/ACTUAL") ? firstExtraction.replace("/ACTUAL", "").toString() : firstExtraction;

                    String secondExtraction = URLDecoder.decode(firstExtraction, "UTF-8");
                    selectedImage = Uri.parse(secondExtraction);
                } catch (UnsupportedEncodingException e) {

                } catch (Exception e) {

                }
            }
        }

Post a Comment for "Android 5.1.1 Lollipop Return Null File Path If Image Chosen From Gallery"