B4J Code Snippet Sharing the goodness: Useful methods

Mashiane

Expert
Licensed User
Hi

Mashy's B4J Overview

I'm new to b4j and have just finished my project in it which is a helper for me in relation to php generation. I shared my creation here. As I am working on an updated version, I needed some functionality on the listview,e.g. returning all items as a map, search for a text or searching for a tag property. Whilst this will start with code on a listview, I intend to collect my snippets here.

B4X:
'Description: add two lines to a listview
'Tag: listview, add two lines
Sub ListViewAddTwoLines(lv As ListView, Line1 As String, Line2 As String, Value As Object)
   Dim ap As AnchorPane
   ap.Initialize("")
   Dim lbl1, lbl2 As Label
   lbl1.Initialize("")
   lbl1.Text = Line1                
   lbl1.Font = fx.DefaultFont(14)
   lbl2.Initialize("")
   lbl2.Text = Line2
   lbl2.Font = fx.DefaultFont(12)
   ap.AddNode(lbl1, 0, 0, lv.Width, 20dip)
   ap.AddNode(lbl2, 0, 25dip, lv.Width, 20dip)
   lv.Items.Add(ap)
   lbl1.Tag = Value
End Sub
B4X:
'Description: add a single line to a listview
'Tag: listview, add single line
Sub ListViewAddOneLine(lv As ListView, Line1 As String, Value As Object)
  Dim ap As AnchorPane
  ap.Initialize("")
  Dim lbl1 As Label
  lbl1.Initialize("")
  lbl1.Text = Line1                
  lbl1.Font = fx.DefaultFont(14)
  lbl1.Tag = Value
  ap.AddNode(lbl1, 0, 0, lv.Width, 20dip)
  lv.Items.Add(ap)
End Sub
B4X:
'Description: search for tag from a listview and return boolean
'Tag: b4j, listview, text, search
Sub ListViewTagExist(lstView As ListView, searchTag As String) As Boolean
    Dim l As List
    Dim i As Int
    Dim t As Int
    Dim m As Map
    Dim txt As String
    searchTag = searchTag.ToLowerCase
    ' get all items as a list
    l = ListViewGetItems(lstView)
    t = l.Size - 1
    For i = 0 To t
        m = l.Get(i)
        txt = m.Get("tag")
        txt = txt.ToLowerCase
        If txt = searchTag Then
            Return True
        End If
    Next
    Return False
End Sub
B4X:
'Description: search for text from a listview and return boolean
'Tag: b4j, listview, text, search
Sub ListViewTextExist(lstView As ListView, searchText As String) As Boolean
    Dim l As List
    Dim i As Int
    Dim t As Int
    Dim m As Map
    Dim txt As String
    searchText = searchText.ToLowerCase
    ' get all items as a list
    l = ListViewGetItems(lstView)
    t = l.Size - 1
    For i = 0 To t
        m = l.Get(i)
        txt = m.Get("text")
        txt = txt.ToLowerCase
        If txt = searchText Then
            Return True
        End If
    Next
    Return False
End Sub
B4X:
'Description: return all items in the listview as a list of maps
'Tag: listview, b4j, map, anchorpane
Sub ListViewGetItems(lstView As ListView) As List
    Dim lstTarget As List
    Dim ap As AnchorPane
    Dim title As Label
    Dim m As Map
    Dim l As List
    l.Initialize
    ' get all the items from the list
    lstTarget = lstView.items
    ' loop through each item
    For I = 0 To lstTarget.Size - 1
        ap = lstTarget.Get(I)
        title = ap.GetNode(0)
        m.Initialize
        m.Put("tag", title.tag)
        m.Put("text", title.Text)
        l.Add(m)
    Next
    Return l
End Sub
B4X:
'Description: return a tag and text of selected listview item as a map
'Tag: listview, map, tag, text
Sub ListViewGetSelected(lstView As ListView) As Map
    Dim m As Map
    m.Initialize
    Dim fsel As Int = lstView.SelectedIndex
    If fsel = -1 Then
        m.Put("tag", "")
        m.Put("text", "")
        m.Put("index","-1")
    Else
        ' get the selected item
        Dim ap As AnchorPane = lstView.SelectedItem
        Dim title As Label = ap.GetNode(0)
        m.Put("tag", title.tag)
        m.Put("text", title.Text)
        m.Put("index", fsel)
    End If
    Return m
End Sub
 
Last edited:

Mashiane

Expert
Licensed User
B4X:
'Description: return all text in the listview as a delimited string
'Tag: listview, b4j, map, anchorpane
Sub ListViewGetTexts(lstView As ListView, Delimiter As String) As String
    Dim lstTarget As List
    Dim sb As StringBuilder
    Dim ap As AnchorPane
    Dim title As Label
    Dim lTot As Int
    Dim lCnt As Int
    sb.Initialize
    ' get all the items from the list
    lstTarget = lstView.items
    ' loop through each item
    lTot = lstTarget.Size - 1
    For lCnt = 0 To lTot
        ap = lstTarget.Get(lCnt)
        title = ap.GetNode(0)
        sb.Append(title.text)
        If lCnt <> lTot Then sb.Append(Delimiter)
    Next
    Return sb.tostring
End Sub
 

Mashiane

Expert
Licensed User
B4X:
'Description: Add listview items from a delimited string
'Tag: listview, b4j, add items
Sub ListViewFromMV(lstView As ListView, MvString As String, Delimiter As String, bClear As Boolean)
    ' do we clear the list first
    If bClear = True Then lstView.Items.clear
    Dim lst() As String: lst = Split(MvString,Delimiter)
    Dim lstTot As Int: lstTot = lst.length - 1
    Dim lstCnt As Int
    Dim lstStr As String
    For lstCnt = 0 To lstTot
        lstStr = lst(lstCnt)
        ListViewAddOneLine(lstView, lstStr,lstStr)
    Next
End Sub
 

Mashiane

Expert
Licensed User
B4X:
'Description: Format string to display in webview with a specified font.
'Tag: webView, font, format text
Sub ToHTML(svalue As String, sFont As String) As String
    Dim sb As StringBuilder
    sb.Initialize
    sb.Append("<html>").Append(CRLF)
    sb.append("<head>").Append(CRLF)
    sb.Append("<style>.f{font-family:").Append(QUOTE).Append(sFont).Append(QUOTE).Append(";}</style>").Append(CRLF)
    sb.Append("</head>").Append(CRLF)
    sb.Append("<body>").Append(CRLF)
    sb.Append("<p class=f>").Append(svalue).Append("</p>").Append(CRLF)
    sb.Append("</body></html>")
    Return sb.ToString
End Sub
 

Mashiane

Expert
Licensed User
B4X:
'Description: Save panel as image to a file
'Tag: panel, save, image
Sub SavePaneToImage(pnl As Pane, imgFile As String)
    Dim Out As OutputStream
    Dim TempImage As Image
    If File.Exists(File.DirApp, imgFile) Then File.Delete(File.dirapp, imgFile)
    Out = File.OpenOutput(File.dirapp, imgFile, False)
    TempImage = pnl.Snapshot
    TempImage.WriteToStream(Out)
    Out.Close
End Sub
 

Mashiane

Expert
Licensed User
B4X:
'Description: Select an item in treeview using its name
'Tag: treeview, select item
Sub TreeViewSetItem(tv As TreeView, s As String)
    Dim ti As TreeItem
    ti = TreeViewSearch(tv.Root, s)
    If ti.IsInitialized = True Then
        Dim jo As JavaObject = tv
        jo.RunMethodJO("getSelectionModel", Null).RunMethod("select", Array(ti))
    End If   
End Sub
 

Mashiane

Expert
Licensed User
B4X:
'Description: return a treeview item using its text property
'Tag: treeview, search, text
Sub TreeViewSearch(Parent As TreeItem, s As String) As TreeItem
   For Each ti As TreeItem In Parent.Children
     If ti.Text = s Then
       Return ti
     End If
     If ti.Children.Size > 0 Then
       Dim res As TreeItem = TreeViewSearch(ti, s)
       If res.IsInitialized Then Return res
     End If
   Next
   Dim res As TreeItem
   Return res
End Sub
 

Mashiane

Expert
Licensed User
B4X:
'Description: Bring panel to front
'Tag: panel, node, Bring2Front
Sub ToFront(n As Node)
    Dim joNode As JavaObject = n
    joNode.RunMethod("toFront", Null)
End Sub
or perhaps

B4X:
Sub BringToFront(n As Node)
   Dim parent As Pane = n.Parent
   n.RemoveNodeFromParent
   parent.AddNode(n, n.Left, n.Top, n.PrefWidth, n.PrefHeight)
End Sub
 

Mashiane

Expert
Licensed User
B4X:
'Define a connection string to Microsoft SQL server
Sub MSSQLConnectionString(serverIP As String,  serverPort As String, serverDB As String) As String
    Dim sb As StringBuilder
    sb.Initialize
    sb.Append("jdbc:jtds:sqlserver://").Append(serverIP).Append(":").Append(serverPort).Append("/").Append(serverDB)
    Return sb.tostring
End Sub
 

Mashiane

Expert
Licensed User
On Process_Globals. Also reference jServer for connection pool
B4X:
    Private pool As ConnectionPool
    Private SQLite As SQL
    Private DatabaseType As Int
    Private UsePool As Boolean
B4X:
'Initialize a connection to MySQL server and returns True if successful
Sub InitializeMySQL(serverIP As String,  serverPort As String, serverDB As String, login As String, password As String, poolSize As Int) As Boolean
    Log("init mysql")
    DatabaseType = 1
    UsePool = True
    Try
        Dim jdbcUrl As String
        jdbcUrl = MySQLConnectionString(serverIP,serverPort,serverDB)
           pool.Initialize("com.mysql.jdbc.Driver", jdbcUrl, login, password)
           ' change pool size...
        Dim jo As JavaObject = pool
        jo.RunMethod("setMaxPoolSize", Array(poolSize))   
        Return True
    Catch
       Log("Last Pool Init Except: "&LastException.Message)
       Return False
    End Try
End Sub

'Initialize a connection to Microsoft SQL server
Sub InitializeMSSQL(serverIP As String,  serverPort As String, serverDB As String ,login As String, password As String, poolSize As Int) As Boolean
    DatabaseType = 2
    Try
        Dim jdbcUrl As String
        jdbcUrl = MSSQLConnectionString(serverIP,serverPort,serverDB)
        pool.Initialize("net.sourceforge.jtds.jdbc.Driver", jdbcUrl, login, password)
        ' change pool size...   
        Dim jo As JavaObject = pool
        jo.RunMethod("setMaxPoolSize", Array(poolSize))
        Return True
    Catch
        Log("Last Pool Init Except: " & LastException.Message)
        Return False
    End Try
End Sub
 
Top