How to load image from relative url in addroid web view

748 views Asked by At

I want to display image from relative url like (//via.placeholder.com/350x150) in android web view Though i can see the html , but the image is broken in web view.

Below is my code to load image from custom html, passed to webview.loadData function.

  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.webview);

    webView = (WebView) findViewById(R.id.webView1);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setDomStorageEnabled(true);
    String customHtml ="<html>\n" +
            "<body>\n" +
            "\n" +
            "    <h3>A demonstration of how to access an IMG element</h3>\n" +
            "\n" +
            "    <img id=\"myImg\" src=\"//via.placeholder.com/350x150\" alt=\"The Pulpit Rock\" width=\"304\" height=\"228\">\n" +
            "\n" +
            "    <p>Click the button to get the URL of the image.</p>\n" +
            "\n" +
            "    <button onclick=\"myFunction()\">Try it</button>\n" +
            "\n" +
            "    <p id=\"demo\"></p>\n" +
            "\n" +
            "    <script>\n" +
            "        function myFunction() {\n" +
            "        var x = document.getElementById(\"myImg\").src;\n" +
            "        document.getElementById(\"demo\").innerHTML = x;\n" +
            "        }\n" +
            "    </script>\n" +
            "\n" +
            "</body>";

   webView.loadData(customHtml, "text/html", "UTF-8");       
}

i have proper permission

  <uses-permission android:name="android.permission.INTERNET"/>;

enter image description here

In my case, main problem is, i always get image with relative url i.e. it won't have http: or https: appended to the url. So what setting or function i should use in android , to display images from relative url protocol.

Please help.

2

There are 2 answers

1
Tung Tran On

This issue is customHtml with wrong src. Replace

src=\"//via.placeholder.com/350x150\"

by src="http://via.placeholder.com/350x150".

0
Jody Jacobus Geers On

/index.html
/bin/image.png

<img src="/bin/image.png" /> will not currently work.
<img src="./bin/image.png" /> will work.