showing image from sdcard with webview not working

倾然丶 夕夏残阳落幕 提交于 2020-01-01 12:32:14

问题


I have downloaded map750.png file in the root of sdcard, but when I try to show it within a webview with some text, only the text is shown. Could you help me to find what is wrong in the code? thanks.

setContentView(R.layout.webview);
    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setAllowFileAccess(true);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setBuiltInZoomControls(true);
    String html = "<html><head></head><body><p>hello</p><img src=\"file://mnt/sdcard/map750.png\" alt=\"alternativo\" /></body></html>";
    mWebView.loadData(html, "text/html","utf-8");

I edit the post to add the solution suggested by oneilse14, thanks!!

setContentView(R.layout.webview);
    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setAllowFileAccess(true);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setBuiltInZoomControls(true);
    String html = "<html><head></head><body><p>hello</p><img src=\"file://mnt/sdcard/map750.png\" alt=\"alternativo\" /></body></html>";
    mWebView.loadDataWithBaseURL("", html, "text/html", "utf-8", "");

回答1:


Check out loadDataWithBaseURL() in the Developer docs

http://developer.android.com/reference/android/webkit/WebView.html

loadData() has certain restrictions on what it can display. This method is able to display local device files like you are trying to do.




回答2:


Try this,

        final String fileName = "file:///mnt/sdcard/1.jpg";
        final String mimeType = "text/html";
        final String encoding = "utf-8";
        final String html = "<img src=\""+fileName+"\">";
        webView.loadDataWithBaseURL("", html, mimeType, encoding, "");



回答3:


Note that the access using the file:// schema can fail due security restrictions.

Another approach is to use the URI of a ContentProvider that handles the local file access. Overwrite openFile(Uri, String) in a subclass of ContentProvider for this approach.



来源:https://stackoverflow.com/questions/8276241/showing-image-from-sdcard-with-webview-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!