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.
publicstatic Uri handleImageUri(Uri uri) {
if (uri.getPath().contains("content")) {
Patternpattern= Pattern.compile("(content://media/.*\\d)");
Matchermatcher= pattern.matcher(uri.getPath());
if (matcher.find())
return Uri.parse(matcher.group(1));
elsethrownewIllegalArgumentException("Cannot handle this URI");
}
return uri;
}
And with this I used the same code I have ever used before for getting the image path:
publicstatic String getRealPathFromURI(Context context, Uri uri) {
Cursorcursor=null;
try {
UrinewUri= handleImageUri(uri);
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(newUri, proj, null, null, null);
intcolumn_index= cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} catch (Exception e){
returnnull;
} 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.
UriselectedImage= data.getData();
if (Build.VERSION.SDK_INT == 22) {
if (selectedImage != null && selectedImage.toString().length() > 0) {
try {
finalStringextractUriFrom= selectedImage.toString();
StringfirstExtraction= extractUriFrom.contains("com.google.android.apps.photos.contentprovider") ? extractUriFrom.split("/1/")[1] : extractUriFrom;
firstExtraction = firstExtraction.contains("/ACTUAL") ? firstExtraction.replace("/ACTUAL", "").toString() : firstExtraction;
StringsecondExtraction= 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"