I\'m trying to set the source of an img tag in my app based on the image chosen from the device image gallery using the PhoneGap/Cordova Camera Plugin.
It has worked
Whenever some uri is passed into it's implicitly decoded from
content://com.android.providers.media.documents/document/image%3A9888 (1)
into
content://com.android.providers.media.documents/document/image:9888 (2)
However, after returning from Intent.ACTION_OPEN_DOCUMENT or Intent.ACTION_GET_CONTENT Android provides you with the read permission for (1), not (2). In this case WebView will expectantly log an error:
java.lang.SecurityException: Permission Denial: reading com.android.providers.media.MediaDocumentsProvider uri content://com.android.providers.media.documents/document/image:9888 from pid=13163, uid=10165 requires android.permission.MANAGE_DOCUMENTS, or grantUriPermission()
or
Unable to open content URL
Code snippet
All you need to resolve the issue is
String uriToUseInWebView = transformForWebView(uri.toString());
private String transformForWebView(String uri) {
for (int i = 0; i < timesDecodingWebView(); i++)
uri = uri.replace("%", Uri.encode("%"));
return uri;
}
private int timesDecodingWebView() {
if (Build.VERSION.RELEASE.equals("4.4.2")) {
return 2;
} else {
return 1;
}
}
in your Java code before passing uri into HTML/JS to ensure that (1) will be actually loaded.
I've tested that on 4.4.2, 4.4.4 and 5.0. The funny part is that Android 4.4.2 decodes the uri internally twice.