B4J Question [B4X] Load Image from AssetsDir in WebView

Discussion in 'B4J Questions' started by b4auser1, Apr 16, 2017.

  1. b4auser1

    b4auser1 Well-Known Member Licensed User

    I used for B4A and B4I, the following code to load an image file from the AssetsDir in html in WebView.

    Code:
    Public Sub UrlForFileFromAssets(a_sFileName As StringAs String
    #If B4A
        
    Return $"file:///android_asset/${a_sFileName}"$
    #End If
    #If B4i
        Return a_sFileName
    #End If
    End Sub
    wvwMain.LoadHtml(HtmlDocText)

    HtmlDocText
    ...
    <img src="${UrlForFileFromAssets(file.jpg)}"/>
    ...

    I tried but failed with the following combinations:

    Code:
    #If B4J
        Return a_sFileName
    #End If

    #If B4J
        Return $"file:///${a_sFileName}"$
    #End If

    #If B4J
        Return $"file:///Files/${a_sFileName}"$
    #End If

    #If B4J
        Return $"file:///{File.DirAssets}/${a_sFileName}"$
    #End If
    How to build path string correctly ?
     
  2. Erel

    Erel Administrator Staff Member Licensed User

    Correct code:
    Code:
    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")}"/>"$)
     
    Last edited: Oct 24, 2017
    naifnas and b4auser1 like this.
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