0

My WebView cannot render an html file stored in the assets folder which contains scripts src (and also CSS path), like

<script type="text/javascript" src="file:///android_asset/emergency.js"></script>

It's showing a white screen.
Any ideas how to fix that?

I've read other answers, but it seems none of them suits my case.

Here is my code from MainActivity.java

    WebView browser = (WebView) this.findViewById(R.id.webView);
    String html = "file:///android_asset/file.html";

    browser.loadDataWithBaseURL("file:///android_asset/", html, "text/html", "utf-8", "");


    browser.getSettings().setJavaScriptEnabled(true);
    browser.getSettings().setSupportZoom(false); 
    browser.getSettings().setBuiltInZoomControls(true);
    browser.getSettings().setDisplayZoomControls(false);

    try {
            browser.loadUrl(html);

        } catch (Exception e) {
            e.printStackTrace();
        }

2 Answers 2

1

If files are in the same location, then html files will automatically determine files locations. So use Relative Paths, but not Absolute.

http://www.coffeecup.com/help/articles/absolute-vs-relative-pathslinks/

Sign up to request clarification or add additional context in comments.

Comments

0

Instead of this:

<script type="text/javascript" src="file:///android_asset/emergency.js"></script>

simply do like this inside your HTML file:

<link rel="stylesheet" type="text/css" href="styles.css" />
<script type="text/javascript" src="scripts.js"></script>

Because the HTML file knows nothing about your assets folder.
But it will easily find the files in the same directory.


Skip this line:

browser.loadDataWithBaseURL("file:///android_asset/", html, "text/html", "utf-8", "");

And just use

browser.loadUrl("file:///android_asset/file.html");

7 Comments

it says about file.html that net::ERR_FILE_NOT_FOUND
Obviously, you need to use the same file names as yours. Mine work in my case, because I have such files in the assets folder, as long as the html which refers them. Take my code as a generic example, but adapt it to your specific case.
I also have all files in the asset folder. but it does not work
Then in the html you must refer them correctly. href="your.css" and src="your.js" - don't add any path before the file names.
I edited my answer - It seems you're not loading the HTML file correctly.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.