Android 5.1.1棒棒糖如果从图库中选择图像,则返回空文件路径。以下代码适用于5.1.1以下的所有设备,但在棒棒糖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。
答案 0 :(得分:9)
现在我最终得到了这个从画廊获取图像。我已经在4.4,5.0.1和5.1.1上对它进行了测试,但它也适用于以前的版本(使用新旧Google照片应用),应该不那么hacky并且不需要检查Android版本
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;
}
有了这个,我使用了之前用过的相同代码来获取图像路径:
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();
}
}
}
答案 1 :(得分:3)
对于Android棒棒糖5.1.1的临时黑客攻击。它现在工作正常。但是我对这个非正式的黑客不满意。
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) {
}
}
}