Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android WebView doesn't load local css file

I am working on an application in Android, where I am using a local html file which includes css files, but It won't work and I have no Idea why. The Java code is like this:

view.loadDataWithBaseURL("file:///android_asset/", content, "text/html", "UTF-8", null);

The HTML code is like this

<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="">


<title>Starter Template for Bootstrap</title>

<!-- Bootstrap core CSS -->
<link href="../css/main.css" rel="stylesheet">
<style>



</style>

The path is correct, Eclipse WebBrowser shows the html Page correct but if I test it on my Device it's without styles. The Logcat throws the Error "Unknown Chromium Error: -6" Thanks a lot in advance

like image 337
user3241778 Avatar asked Oct 20 '25 02:10

user3241778


2 Answers

you cannot refer to this path inside a webview. you probably need to store your css file in assets folder and refer to it dynamically:

put CSS in assets folder, do your manipulation with HTML, but refer to CSS by relative path, and load HTML to WebView by loadDataWithBaseURL() method:

webView.loadDataWithBaseURL("file:///android_asset/", htmlString, "text/html", "utf-8", null);
E.g. you have styles.css file, put it to assets folder, create HTML and load it:

StringBuilder sb = new StringBuilder();
sb.append("<HTML><HEAD><LINK href=\"styles.css\" type=\"text/css\" rel=\"stylesheet\"/></HEAD><body>");
sb.append(tables.toString());
sb.append("</body></HTML>");
webView.loadDataWithBaseURL("file:///android_asset/", sb.toString(), "text/html","utf-8", null); 

from: WebView, add local .CSS file to an HTML page?

like image 131
gaurav5430 Avatar answered Oct 21 '25 17:10

gaurav5430


On a related note, if you're not storing the file in the assets folder and want to use relative paths, Webview on Android sometimes requires dot-slash before relative paths.

<LINK href="./styles/file.css" type="text/css" rel="stylesheet">

See this post

like image 20
senf78 Avatar answered Oct 21 '25 16:10

senf78



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!