Suda.nese Suda.nese - 2 months ago 13
Android Question

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.

Answer

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

Comments