9

I'm trying to load a html string stored in the database which contain a image into a WebView. The image is stored in the internal memory. I am giving a reference to the html string.But it doesn't work. Any help?

String content="<p>Can we have a rotational" +
    " symmetry of order more than 1 whose angle of rotation is&nbsp;</p>\n" +
    "\n <p>(i)&nbsp;<img alt=\"45\\degree\" src=\"file:///storage/emulated/01484890695248.jpg\" /></p>\n" +
    "\n<p>(ii)&nbsp;<img alt=\"35\\degree\" src=\"file:///storage/emulated/01484890697301.jpg\" /></p>";

WebView00.loadDataWithBaseURL("", content, "text/html","UTF-8", "");
WebView00.getSettings();
Charuක
  • 12,953
  • 5
  • 50
  • 88
Bera
  • 145
  • 1
  • 2
  • 11

4 Answers4

21

Try like this

String base = Environment.getExternalStorageDirectory().getAbsolutePath().toString();
String imagePath = "file://"+ base + "/image_name.jpg";
String html = "<html><head></head><body> <img src=\""+ imagePath + "\"> </body></html>";
webView.loadDataWithBaseURL("", html, "text/html","utf-8", "");
Charuක
  • 12,953
  • 5
  • 50
  • 88
3

Put the images in your assets folder. Then use the corresponding prefix

file:///android_asset/
Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134
1

In latest android versions we cant access resources such as assets , files from storage. https://developer.android.com/reference/androidx/webkit/WebViewAssetLoader is best guide to proceed. WebViewAssetLoader and its internal classes helps to access them.

you can check the below sample code.

    final WebViewAssetLoader assetLoader = new WebViewAssetLoader.Builder()
            .addPathHandler("/assets/", new WebViewAssetLoader.AssetsPathHandler(this)) //****for assets****
            .addPathHandler("/images/", new WebViewAssetLoader.InternalStoragePathHandler(context, getFilesDir()))//****for files****
            .build();

    webView.setWebViewClient(new WebViewClient() {
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view,
                                                          WebResourceRequest request) {
            return assetLoader.shouldInterceptRequest(request.getUrl());
        }
    });

    String assetsPic = "<img width='42px' height='58px' src='https://appassets.androidplatform.net/assets/pic.png'/>";
    String storagePic = "<img width='42px' height='58px' src='https://appassets.androidplatform.net/images/pic.jpg'/>";
    webView.loadData(assetsPic+"<br>"+storagePic, "text/html", "UTF-8");
shobhan
  • 1,460
  • 2
  • 14
  • 28
0

The problem was in the file path

file:///storage/emulated/01484890695248.jpg

would be

file:///storage/emulated/0/01484890695248.jpg

Thanks @Charuක for the help..

Bera
  • 145
  • 1
  • 2
  • 11