Android Code Snippet Using Webview files in the Assets Directory

Status
Not open for further replies.
I'm writing this because I could not find a quick answer to this question:

How do I load a set of web pages in a Webview that are contained in the Assets Directory?

This is how you load a page:

B4X:
WebView1.LoadUrl("file:///android_asset/form.html")

If you try this in DEBUG mode however, it will not work directly.

You also have to add this to the Project Attributes Region

B4X:
    #DebuggerForceStandardAssets : true

NB You might think that you should use this construct

B4X:
        Dim url="file:///" & File.Combine(File.DirAssets, "form.html")
        Log("Loading " & url)
        WebView1.LoadUrl(url)

Unfortunately File.DirAssets does not point to the folder that is required namely android_asset

If your HTML files refer to other files in the Assets folder, they will not be found if you refer to them like this:

B4X:
<link rel="stylesheet" type="text/css"
href="view.css" media="all" />

To get get the right reference use this:

B4X:
  <link rel="stylesheet" type="text/css"
href="android_asset/view.css" media="all" />

(in fact in this case you could could put both links in your code, only one of them will get found. If you open the base file in an HTML viewer, it will get the CSS file from the first link)

I hope this saves someone else some time.
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
Better solution that doesn't require you to disable the virtual assets folder and is cross platform:
B4X:
'Depends on JavaObject
Sub WebViewAssetFile (FileName As String) As String
   #if B4J
     Return File.GetUri(File.DirAssets, FileName)
   #Else If B4A
     Dim jo As JavaObject
     jo.InitializeStatic("anywheresoftware.b4a.objects.streams.File")
     If jo.GetField("virtualAssetsFolder") = Null Then
       Return "file:///android_asset/" & FileName.ToLowerCase
     Else
       Return "file://" & File.Combine(jo.GetField("virtualAssetsFolder"), _
       jo.RunMethod("getUnpackedVirtualAssetFile", Array As Object(FileName)))
     End If
   #Else If B4i
     Return $"file://${File.Combine(File.DirAssets, FileName)}"$
   #End If
End Sub

Usage:
B4X:
WebView1.LoadHtml($"<img src="${WebViewAssetFile("1.png")}"/>"$)
It will work in debug mode and release mode.
 
Last edited:

tsteward

Well-Known Member
Licensed User
Longtime User
How can I do the same except the image file is in a directory contained within string DBFileDir

Which was obtained by DBFileDir = Starter.rp.GetSafeDirDefaultExternal("")

These are images I create and save in the run that I then want to display in a webview.
 
Status
Not open for further replies.
Top