Android Code Snippet Using Webview files in the Assets Directory

Discussion in 'Code Snippets' started by Derek Johnson, Aug 12, 2016.

  1. Derek Johnson

    Derek Johnson Active Member Licensed User

    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:

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

    You also have to add this to the Project Attributes Region

    #DebuggerForceStandardAssets : true
    NB You might think that you should use this construct

    Dim url="file:///" & File.Combine(File.DirAssets, "form.html")
    Log("Loading " & 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:

    <link rel="stylesheet" type="text/css"
    "view.css" media="all" />
    To get get the right reference use this:

    <link rel="stylesheet" type="text/css"
    "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.
    stanks, arced, Phayao and 1 other person like this.
  2. Erel

    Erel Administrator Staff Member Licensed User

    Better solution that doesn't require you to disable the virtual assets folder and is cross platform:
    'Depends on JavaObject
    Sub WebViewAssetFile (FileName As StringAs String
    #if B4J
         Return File.GetUri(File.DirAssets, FileName)
       #Else If B4A
         Dim jo As JavaObject
         If jo.GetField("virtualAssetsFolder") = Null Then
           Return "file:///android_asset/" & FileName.ToLowerCase
           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
    WebView1.LoadHtml($"<img src="${WebViewAssetFile("1.png")}"/>"$)
    It will work in debug mode and release mode.
    Last edited: Nov 21, 2017
  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice