B4J Question [B4X] Load Image from AssetsDir in WebView

b4auser1

Well-Known Member
Licensed User
Longtime User
I used for B4A and B4I, the following code to load an image file from the AssetsDir in html in WebView.

B4X:
Public Sub UrlForFileFromAssets(a_sFileName As String) As 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:

B4X:
#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 ?
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
Correct code:
B4X:
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")}"/>"$)
 
Last edited:
Upvote 0
Top