Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a webpage on WebView from locally-created folder?

Working with Android-Studio, I am trying to use WebView to load a local html file that contains javascript.

First, I created an assets folder inside the Java folder. Then, I created two folders inside assets folder: html and scripts. I put my index.html page inside html folder and the index.js file inside scripts folder. The two paths look like the following in Android-Studio:

  1. app/java/assets/html/index.html
  2. app/java/assets/scripts/index.js

Now, when I try to load the index.html, I use the following syntax:

myWebView.loadUrl("file:///assets/html/index.html");

but it is not working. I also used each of the following:

myWebView.loadUrl("file://assets/html/index.html");

myWebView.loadUrl("file://android_assets/html/index.html");

myWebView.loadUrl("file:///android_assets/html/index.html");

Still, when the page loads, it shows "Webpage not available"!!

The app works fine, the intent start and a webpage loads with the above warning message.

  1. What is right syntax to load the webpage from a local-created folder ?
  2. What is the right syntax for loading index.js inside the index.html ?

Here is the code:

    public class DisplayMessageActivity extends Activity {

    private WebView myWebView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display_message);

        myWebView = (WebView) findViewById(R.id.webview);
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.loadUrl("file:///android_assets/html/index.html"); // doesn't work
        // myWebView.loadUrl("http://www.example.com"); // works
    }

UPDATE

Here is the index.html :

<html>
<header><title>This is title</title></header>
<body>
Hello world
</body>
</html>

No javascript at the moment.

like image 318
McLan Avatar asked Jan 19 '26 10:01

McLan


2 Answers

Create assets folder under main ( not inside java ) and then use

myWebView.loadUrl("file:///android_asset/html/index.html");

not

myWebView.loadUrl("file:///android_asset**s**/html/index.html");

enter image description here

like image 56
Amod Gokhale Avatar answered Jan 21 '26 23:01

Amod Gokhale


Use above answer just replace

webView.loadUrl("file://android_asset/index.html");

with webView.loadUrl("file:///android_asset/index.html");

like image 33
Vaibhav Kadam Avatar answered Jan 22 '26 01:01

Vaibhav Kadam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!