1

I have a custom error page to show in a Webview, that is stored in the default asset folder C:\Users\User\StudioProjects\Appname\app\src\main\assets\error.html

In the onReceivedError method of a WebViewClient I load the page like this view.loadUrl("file:///android_asset/error.html");

It worked fine when I coded and tested it, however the weird thing is, I tested it again, the Webview showed this error
The webpage at file:///android_asset/error.html could not be loaded because: net::ERR_FILE_NOT_FOUND

I tried the solution from https://stackoverflow.com/a/37994555/4722232, it worked for the html, but I have a logo in it and having the same problem and in the log I'm getting

"Not allowed to load local resource: file:///android_asset/logo.png", source: about:blank (0)

Any help would be greatly appreciated

1 Answers1

1
  1. Read the file from asset and load into WebView
val htmlFile = "file:///android_asset/file_name.extension" //e.g. index.html
webView.loadUrl(htmlFile)

asset folder must be inside main

  1. Get the content of the file from the asset folder and then load into WebView
val inputStream = assets.open("file_name.extension")
val buffer = BufferedInputStream(inputStream)
val bytes = buffer.readBytes()
val content = String(bytes)
buffer.close()
webView.loadData(String(content), "text/html", "utf-8")
  1. Read the file from raw folder

res -> raw -> file_name.extension

val inputStream = resources.openRawResource(R.raw.index)
val buffer = BufferedInputStream(inputStream)
val bytes = buffer.readBytes()
val content = String(bytes)
buffer.close()
webView.loadData(String(content), "text/html", "utf-8")

You can use Kotlin Extensions to streamline this process

assets.open("file_name.extension").bufferedReader().use { br ->
    webView.loadData(br.readText(), "text/html", "utf-8")
}

Make sure your file_name.extension be lowercase and only contain _ if they are in either res or assets folder.

Arrowsome
  • 2,649
  • 3
  • 10
  • 35
  • Thank you for the answer. I used the inputStream, the html file works now, but my image is still not getting displayed. I moved the image to `main\res\drawable`. Would the path to it then be `` ? – Filoména Petržlénová Jun 25 '20 at 17:49
  • @FiloménaPetržlénová Now I get it. you are using the image for HTML file and that's okay to put it inside the `assets` folder. put it back in `assets` folder and that exact location depends on `` inside your HTML. so the `assets` folder is your root folder. – Arrowsome Jun 25 '20 at 18:14
  • yes, I had it in the asset folder, but I still got the `Unable to open asset URL: file:///android_asset/logo.png` error. In the html file it was like this `` – Filoména Petržlénová Jun 26 '20 at 10:12
  • @FiloménaPetržlénová Share your HTML file if possible so I can test it locally. – Arrowsome Jun 26 '20 at 10:15