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:

    Code:
    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

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

    Code:
    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:

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

    Code:
    <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.
     
    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:
    Code:
    'Depends on JavaObject
    Sub WebViewAssetFile (FileName As StringAs 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:
    Code:
    WebView1.LoadHtml($"<img src="${WebViewAssetFile("1.png")}"/>"$)
    It will work in debug mode and release mode.
     
    Last edited: Nov 21, 2017
Loading...
  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