Loading local html file in webView android

2019-02-02 13:52发布

问题:

I have to load an existing html file into a WebView that is located at this path in the file system:

/data/data/com.example.example/files/file.html

But, when the WebView loads it, I don't see anything. Who can help me?

WebView code (assuming path is the path I've written above):

 WebView webView = (WebView)findViewById(R.id.webView1);

  File htmlFile = new File(path);
    if(htmlFile.exists())
    {
        webView.loadUrl(htmlFile.getAbsolutePath());

    }

回答1:

Try this, adding in a file:/// and doing it a little differently:

WebView webView = (WebView)findViewById(R.id.webView1);
webview.loadUrl("file:///data/data/com.example.example/files/file.html");  

Instead of this, however, you could just put the file into your assets folder in the source code, and then do this:

WebView webView = (WebView)findViewById(R.id.webView1);
webview.loadUrl("file:///android_asset/file.html");


回答2:

The html file should be placed in the assets folder, which will belong in the root directory of your project.

So move your file to in case of eclipse

assets/index.html

In an Android Studio project use this folder:

/app/src/main/assets/index.html

Now use

WebView wv= (WebView)findViewById(R.id.webView1);
wv.loadUrl("file:///android_asset/index.html");


回答3:

You need to implement a ContentProvider to map local files to uris as explained in this link how to display a local file into Android Webview

or you just load any html page from Assets folder like below:

 WebView wv= (WebView)findViewById(R.id.webView1);
 wv.loadUrl("file:///android_asset/yourfile.html");
 wv.getSettings().setJavaScriptEnabled(true);