如果从库图像选择的Andr​​oid 5.1.1棒棒糖返回NULL文件路径棒棒糖、路径、文件、库图

2023-09-06 02:24:59 作者:不拽,怎么赢世界

安卓5.1.1棒棒糖返回空文件路径,如果从画廊的图像选择。下面code正常工作在低于5.1.1的所有设备,但在棒棒糖不起作用5.1.1

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 contentUri = data.getData();
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();
        }
    }

cursor.getString(Column_Index中)返回null。

推荐答案

现在我已经结束了与此获取从画廊的形象,我已经在4.4,5.0.1和5.1.1,但应该对其进行了测试在previous版本太(与新老谷歌照片的应用程序),应少哈克,并不需要在Android版本检查

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 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) {
    Pattern pattern = Pattern.compile("(content://media/.*\\d)");
    if (uri.getPath().contains("content")) {
        Matcher matcher = pattern.matcher(uri.getPath());
        if (matcher.find())
            return Uri.parse(matcher.group(1));
        else
            throw new IllegalArgumentException("Cannot handle this URI");
    } else
        return uri;
}

和本我用同样的$ C $词曾经使用之前获取图像路径:

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

让我知道这对你的工作:)

Let me know if this work for you :)

更新6 2015年10月 随着最新版本,并与一切的Andr​​oid工作室更新的问题消失了,事情已更新,现在这个解决办法不再需要

UPDATE 6 October 2015 With latest version and with everything updated in Android Studio the problem is gone, something has been updated and now this workaround is no longer needed