Android Code Snippet Sharing the goodness: Some useful methods

Hi

This is a collection of methods that I have collected here in b4a, perhaps one can find them useful..

B4X:
'Description: Return Left part of a string
'Tags: left method, string
Sub Left(Text As String, Length As Long)As String
   If Length>Text.Length Then Length=Text.Length
   Return Text.SubString2(0, Length)
End Sub

'Description: Return Right part of a string
'Tags: right method, string
Sub Right(Text As String, Length As Long) As String
   If Length>Text.Length Then Length=Text.Length
   Return Text.SubString(Text.Length-Length)
End Sub

'Description: Return the Mid portion of a string
'Tags: mid method, string
Sub Mid(Text As String, Start As Int, Length As Int) As String
   Return Text.SubString2(Start-1,Start+Length-1)
End Sub

'Description: Returns an array from a delimited string
'Tags: split method, string
Sub Split(Text As String, Delimiter As String) As String()
   Return Regex.Split(Delimiter,Text)
End Sub

'Description: Returns the length of a string
'Tags: length of string, len
Sub Len(Text As String) As Int
    Return Text.Length
End Sub

'Description: Replace a string within a string
'Tags: Replace function, string
Sub Replace(Text As String, sFind As String, sReplaceWith As String) As String
    Return Text.Replace(sFind, sReplaceWith)
End Sub

' Description: Return a string in lowercase
'Tags: lower case string, lcase
Sub LCase(Text As String) As String
    Return Text.ToLowerCase
End Sub

'Description: Return a string in uppercase
'Tags: upper case, ucase
Sub UCase(Text As String) As String
    Return Text.ToUpperCase
End Sub

'Description: Trim a string
'Tags: trim, string
Sub Trim(Text As String) As String
    Return Text.Trim
End Sub

'Description: Return position of sub string within a string
'Tags: indexof, position
Sub InStr(Text As String, sFind As String) As Int
    Return Text.IndexOf(sFind)
End Sub

'Description: Return position of a sub string within a string starting from a position
'Tags: indexof, position, string
Sub InStr1(iStart As Int, Text As String, sFind As String) As Int
    Return Text.IndexOf2(Text, iStart)
End Sub

'Description: Return position of a substring within a string starting from the back
'Tags: instrrev, string
Sub InStrRev(Text As String, str As String) As Int
    Return Text.LastIndexOf(str)
End Sub

'Description: Returns true if a string contains another string
'Tag: string, contains
Sub Contains(Text As String, sFind As String) As Boolean
    Return Text.Contains(sFind)
End Sub

B4X:
'Description: check if device has internet connection
'Tags: internet,connection
Sub HasInternet() As Boolean
    Dim  Server As ServerSocket
    Server.Initialize(0, Null)
    If Server.GetMyIP = "127.0.0.1" Then 'Test for internet connection
        Return False
    Else
        Return True
    End If
End Sub

'Description: sum all the values in a list
'Tags: list,sum
Sub ListSum(lst As List) As String
    Dim lTot As Int = lst.Size - 1
    Dim lCnt As Int
    Dim lStr As Int
    Dim lSum As Int = 0
 
    For lCnt = 0 To lTot
        lStr = lst.Get(lCnt)
        lSum = lSum + lStr
    Next
    Return lSum
End Sub

B4X:
'Description: Returns True if the CurrentDate and the CompareToDate are within X number of days(DateRange)
'of each other. Otherwise False will be returned.
'Tags: Date, search, range
Sub SearchDate(CurrentDate As String, CompareToDate As String, DateRange As Int) As Boolean
    Dim DayOfYearCompareDate, DayOfYearCurrentDate As Long
    If ValidDate(CurrentDate) And ValidDate(CompareToDate) Then
    Else
        Return False
    End If
    DayOfYearCompareDate = DateTime.GetDayOfYear(DateTime.DateParse(CompareToDate))
    DayOfYearCurrentDate = DateTime.GetDayOfYear(DateTime.DateParse(CurrentDate))
    If DayOfYearCompareDate >= DayOfYearCurrentDate And DayOfYearCompareDate <= (DayOfYearCurrentDate + DateRange) Then
        Return True
    Else
        Return False
    End If
End Sub

B4X:
'Description: Return the date tomorrow in ticks
'Tags: date, tomorrow
Sub Tomorrow() As Long
    Dim Tom As Long
    Tom = DateTime.Add(DateTime.Now, 0, 0, 1)
    Return DateTime.Date(Tom)
End Sub

'Description: Convert a json file to a map
'Tags: json, map, conversion
Sub JsonFileToMap(Dir As String, FileName As String) As Map
    Dim JSON As JSONParser
    Dim Map1 As Map
    JSON.Initialize(File.ReadString(Dir, FileName))
    Map1 = JSON.NextObject
    Return Map1
End Sub

'Description: Convert a json string to a map
'Tags: json, string, map, conversion
Sub Json2Map(jsonText As String) As Map
    Dim json As JSONParser
    Dim Map1 As Map
    json.Initialize(jsonText)
    Map1 = json.NextObject
    Return Map1
End Sub

B4X:
'Description: Returns whether the passed date is valid or not
'Tags: date validation,date
Public Sub ValidDate(ChkDate As String) As Boolean
    Private dcf As Int
    Private GoodDate As String
    dcf = 0
    Try
        GoodDate = DateTime.DateParse(ChkDate)
    Catch
        GoodDate = ""
        dcf = 1
    End Try
    If dcf = 0 Then
        Return True
    Else
        Return False
    End If 
End Sub

'Description: Returns a new date when adding them to an existing date
'Tags: Date, addition, calculation
Sub DateAdd(mDate As String, HowManyDays As Int) As String
    Dim ConvertDate, NewDateDay As Long
    ConvertDate = DateTime.DateParse(mDate)
    NewDateDay = DateTime.Add(ConvertDate, 0, 0, HowManyDays)
    Return DateTime.Date(NewDateDay)
End Sub

'Description: Returns the number of days that have passed between two dates.
'Pass the dates as a String
'Tags: Date, differences, calculation
Sub DateDiff(CurrentDate As String, OtherDate As String) As Int
    Dim CurrDate, OthDate, MyNewDate As Long
    CurrDate = DateTime.DateParse(CurrentDate)
    OthDate = DateTime.DateParse(OtherDate)
    Return (CurrDate-OthDate)/(DateTime.TicksPerDay)
End Sub


'Description: Return the position of a string within another
'Tags: at, string position
Sub At(Text As String,SearchFor As String) As Int
    Return Text.IndexOf(SearchFor)
End Sub

'Description: Return the left trimmed string from another
'Tags: ltrim, trim, left
Sub Ltrim(Text As String) As String
    Do While Left(Text, 1) =" "
        Text = Right(Text, Len(Text)-1)
    Loop
    Return Text
End Sub

'Description: Return the right trimmed string from another
'Tags: rtrim, trim, string
Sub Rtrim(Text As String) As String
    Do While Right(Text, 1) =" "
        Text = Left(Text, Len(Text)-1)
    Loop
    Return Text
End Sub

'Description: VB val function equivalent to return all numeric values in a string
'Tags: val, string, numericonly
Sub Val(Text As String) As String
    Do While IsNumber(Right(Text,1))=False Then
        If Len(Text) >0 Then
            Text=Left(Text, Len(Text)-1)
        Else
            Exit
        End If 
    Loop
    If Len(Text) > 0 Then
        Return Text + 0
    Else
        Return 0
    End If 
End Sub

'Description: vb IIf equivalent function
'Tags:iif
Sub iif(Text As String, Text1 As String, Text2 As String) As String
    If Text = True Then Return Text1 Else Return Text2
End Sub

'Description: Pauses operation
'Tags: pause, execution
Sub Pause(Tvar As Int)
    Dim Tstart As Long
    Tstart = DateTime.Now
    Do While DateTime.Now-Tstart < (Tvar*1000)
    Loop
End Sub

B4X:
'Description: Return space made of number of
'Tags: space
Sub Space(HM As Int) As String
    Dim RS As String = ""
    Do While Len(RS) < HM
        RS = RS & " "
    Loop
    Return RS
End Sub

B4X:
'Description: Load a combobox from a multi value delimited string
'Tags: combobox, picker, delimited
Sub ComboBoxFromMV(cbo As Spinner, sValues As String, sDelim As String, bClear As Boolean, xPrefix As String)
    ' load a combo box from multi value fields
    If bClear = True Then cbo.Clear
    Dim spvalues() As String
    Dim i As Int
    Dim itot As Int
    Dim ivalue As String
    spvalues = Regex.Split(sDelim, sValues)
    itot = spvalues.length - 1
    For i = 0 To itot
        ivalue = spvalues(i)
        ivalue = ivalue.Trim
        ivalue = xPrefix & ivalue
        cbo.Add(ivalue)
    Next
End Sub

'Description: Returns a list from a multi value delimited string
'Tags: List, multi-value string,delimited
Sub ListFromMV(lst As List, sValues As String, sDelim As String, bClear As Boolean, bClean As String, xPrefix As String)
    ' convert multi value fields to a list
    If bClear = True Then lst.Initialize
    Dim spvalues() As String
    Dim i As Int
    Dim itot As Int
    Dim ivalue As String
    spvalues = Regex.Split(sDelim, sValues)
    itot = spvalues.length - 1
    For i = 0 To itot
        ivalue = spvalues(i)
        ivalue = ivalue.Trim
        ivalue = xPrefix & ivalue
        If bClean = True Then ivalue = CleanValue(ivalue)
        If lst.IndexOf(ivalue) = -1 Then lst.Add(ivalue)
    Next
End Sub

'Description: Return a cleaned string without the values specified only
'Tags: string, replace
Public Sub CleanValue(sValue As String) As String
    sValue = sValue.replace(" ","")
    sValue = sValue.Replace(".","")
    sValue = sValue.Replace("-","")
    sValue = sValue.Replace("&","")
    sValue = sValue.Trim
    Return sValue
End Sub

'Description: Copy values from one combobox to another
'Tags: combobox, picker, copy
Sub ComboBoxCopy(cboSource As Spinner, cboTarget As Spinner)
    cboTarget.Clear
    Dim i As Int
    Dim itot As Int
    Dim ivalue As String
    itot = cboSource.Size - 1
    For i = 0 To itot
        ivalue = cboSource.GetItem(i)
        cboTarget.Add(ivalue)
    Next
End Sub

B4X:
'Description: Return true if device being used is a tablet
'Tags: device size
Sub IsTablet() As Boolean
    Dim lv As LayoutValues
    lv = GetDeviceLayoutValues
       Dim DeviceSize As Int = lv.ApproximateScreenSize
    If DeviceSize >= 6 Then
        Return True
    Else
        Return False
    End If
End Sub

B4X:
'Description: search for a string in a multi value string and return position
'Tags: search, multi-value string
Sub MvSearch(searchvalues As String,strsearch As String,delim As String) As Int
    If searchvalues.length = 0 Then Return -1
    Dim spvalues() As String
    Dim i As Int, itot As Int, ivalue As String
    spvalues = Regex.Split(delim,searchvalues)
    strsearch = strsearch.ToLowerCase
    itot = spvalues.length - 1
    For i = 0 To itot
        ivalue = spvalues(i)
        ivalue = ivalue.ToLowerCase
        If ivalue = strsearch Then Return i
    Next
    Return -1
End Sub
 
Last edited:

Mahares

Expert
Licensed User
Longtime User
Pad a string to the right with a specific character

@Mashiane:
You code should be like this:
B4X:
Sub PadRight(Value As String, MaxLen As Int, PadChar As String) As String
    Dim  intOrdNoLen As Int = Value.Length
    Dim i As Int
    For i = 1 To (MaxLen - intOrdNoLen) Step 1
        Value =  Value & PadChar
    Next
    Return Value   'displays: Mashianexxxxxxxxxxxx
End Sub
B4X:
Log(PadRight("mashiane", 20, "x") )    'displays: Mashianexxxxxxxxxxxx

But, if you really want to kill 2 birds with one stone and make it pad right or left, here is how I do it:
B4X:
Sub Pad(Value As String, MaxLen As Int, PadChar As String, right As Boolean) As String
    Dim  intOrdNoLen As Int = Value.Length
    Dim i As Int
    For i = 1 To (MaxLen - intOrdNoLen) Step 1
        If right Then
            Value =  Value & PadChar
        Else
            Value = PadChar & Value
        End If
    Next
    Return Value
End Sub
B4X:
Log($"${Pad("Mashiane", 20, "x", True)}"$)   'displays: Mashianexxxxxxxxxxxx
 

Mashiane

Expert
Licensed User
Longtime User
'Description: return the position of a map key
'Tag: map, key, indexof
B4X:
'return the position of a map key
private Sub MapGetKeyPos(strKey As String, mp As Map) As Int
    Dim kcnt As Int
    Dim ktot As Int = mp.Size - 1
    Dim kstr As String
    For kcnt = 0 To ktot
        kstr = mp.GetKeyAt(kcnt)
        If kstr.ToLowerCase = strKey.ToLowerCase Then
            Return kcnt
        End If
    Next
    Return -1
End Sub
 

LucaMs

Expert
Licensed User
Longtime User
It should work also this way:

Dim m As Map
Dim lst As List = m.Keys
Return lst.IndexOf(strKey)

Without the kcnt loop.

(I suppose that you cannot write directly Return m.Keys.IndexOf(strKey) because Keys is an Array, not a List)
 

Mashiane

Expert
Licensed User
Longtime User
It should work also this way:

Dim m As Map
Dim lst As List = m.Keys
Return lst.IndexOf(strKey)

Without the kcnt loop.

(I suppose that you cannot write directly Return m.Keys.IndexOf(strKey) because Keys is an Array, not a List)
Would be nice though of such a method existed, makes things easy. Also the case sensitivity now becomes another issues as the keys are CaseSensiTive.
 

Mahares

Expert
Licensed User
Longtime User
If kstr.ToLowerCase = strKey.ToLowerCase
As you mentioned in your previous post, Keys are case sensitive. You should replace this:
B4X:
If kstr.ToLowerCase = strKey.ToLowerCase Then
with this:
B4X:
If kstr = strKey Then

Suppose I have this map:
B4X:
Dim Mm As Map
    Mm.Initialize
    Mm.Put("Sigla", "AA")
    Mm.Put("Provincia", "Prima provincia")
    Mm.Put("Ipt", "30%")
    Mm.Put("Perc", "30")
    Mm.Put("IPT", "33%")

Log(MapGetKeyPos("IPT", Mm) ) 'will always return the 2 with your code. Whereas if you remove the case validation, it will find the correct one which is 4.
Please provide examples when you post snippets, so the rest of us can better understand. You have a very good thing going. Thank you for your benevolence.
 

Mashiane

Expert
Licensed User
Longtime User
As you mentioned in your previous post, Keys are case sensitive. You should replace this:
B4X:
If kstr.ToLowerCase = strKey.ToLowerCase Then
with this:
B4X:
If kstr = strKey Then

Suppose I have this map:
B4X:
Dim Mm As Map
    Mm.Initialize
    Mm.Put("Sigla", "AA")
    Mm.Put("Provincia", "Prima provincia")
    Mm.Put("Ipt", "30%")
    Mm.Put("Perc", "30")
    Mm.Put("IPT", "33%")

Log(MapGetKeyPos("IPT", Mm) ) 'will always return the 2 with your code. Whereas if you remove the case validation, it will find the correct one which is 4.
Please provide examples when you post snippets, so the rest of us can better understand. You have a very good thing going. Thank you for your benevolence.
I've learned the hard way during my scenarios that it's just better to lowercase my map keys. They can create havoc if not handled with care (not the maps, but how you code them)
 

Mashiane

Expert
Licensed User
Longtime User
The attached bal file is for those ones who need TwoLinesAndBitMap for CustomView controls.

B4X:
Sub TwoLinesAndBitmapSetting(LabelTextColor As Int, LabelSize As Int, SecondLabelTextColor As Int, SecondLabelSize As Int)
    FirstLabel.TextColor = LabelTextColor
    FirstLabel.TextSize = LabelSize
    SecondLabel.TextColor = SecondLabelTextColor
    SecondLabel.TextSize = SecondLabelSize
End Sub

Sub AddTwoLinesAndBitmap2(LabelText As String, SecondLabelText As String, bmp As Bitmap, Index As Object) As Panel
    Dim pan As Panel
    pan.Initialize("")
    Activity.AddView(pan,0dip,0dip,100%x,100%y)
    pan.LoadLayout("vTwoLinesAndBitMap")
    pan.Color = Colors.Transparent
    FirstLabel.Text = LabelText
    SecondLabel.Text = SecondLabelText
    TwoLinesAndBitmapSetting(Colors.Black,16dip,Colors.Black,13dip)
    Image.BitMap = bmp
    pan.removeView
    pan.Tag = Index
    Return pan
End Sub

This could be useful in the ImageLoader functionality.

Usage:

B4X:
Dim pnl As Panel = AddTwoLinesAndBitmap2("Label1", "SecondLabel", LoadBitMap(File.DirAssets,"x.png"),"mykey")
        lstItems.Add(pnl,"90dip","mykey")

The height of the twolinesbitmap in b4a is 90dip and the label sizes are 19.5 and 16.5 respectively. Also note the bal script contents for more.

That's all folks.
 

Attachments

  • vtwolinesandbitmap.bal
    2.5 KB · Views: 217
Last edited:

Mashiane

Expert
Licensed User
Longtime User
Making my CustomListViewWork...

I wanted to set badges within the views inside my customview, however these were not working by finding the label to set a badge on, thus I needed to remove and create the items. I adjusted my CustomListView to have this method..

orders.png


B4X:
'Adds a custom item at the specified index.
Public Sub ReplaceAt(Index As Int, pnl As Panel, ItemHeight As Int, Value As Object)
    RemoveAt(Index)
    InsertAt(Index, pnl, ItemHeight, Value)
End Sub

And my up and down code...

B4X:
Sub imgUp_Click
    Dim imgV As ImageView
    imgV = Sender
    msa.with(mst.Wobble).duration(500).playon(imgV)
    Dim idx As Int = lstRecordsC.GetItemFromView(imgV)
    Dim pnl As Panel = lstRecordsC.GetPanel(idx)
    jobMap = pnl.Tag
    Item_no = jobMap.Get("Item_no")
    Qty = jobMap.Get("qty")
    Qty = Qty + 1
    jobMap.Put("qty",Qty)
    pnl = AddItem(jobMap)
    lstRecordsC.ReplaceAt(idx,pnl,lstRecordsC.DefaultItemHeight,Item_no)
End Sub

Sub imgDown_Click
    Dim imgv As ImageView
    imgv = Sender
    msa.with(mst.wobble).duration(500).playon(imgv)
    Dim idx As Int = lstRecordsC.GetItemFromView(imgv)
    Dim pnl As Panel = lstRecordsC.GetPanel(idx)
    jobMap = pnl.Tag
    Item_no = jobMap.Get("Item_no")
    Qty = jobMap.Get("qty")
    If Qty > 0 Then
        Qty = Qty - 1
        jobMap.Put("qty",Qty)
        pnl = AddItem(jobMap)
        lstRecordsC.ReplaceAt(idx,pnl,lstRecordsC.DefaultItemHeight,Item_no)
    End If
End Sub
 

Mashiane

Expert
Licensed User
Longtime User
SQLite Things:

I wanted to update some related table columns from one table based on a foreign key in another.

B4X:
sqlCommands.add("update ProgrammesSet set ppBudget = (select IYMAnalysisSet.Projections from IYMAnalysisSet where IYMAnalysisSet.IYMAnalysis_Programmes = ProgrammesSet.Number) where exists (select * from IYMAnalysisSet where IYMAnalysisSet.IYMAnalysis_Programmes = ProgrammesSet.Number)")
    sqlCommands.add("update ProgrammesSet set ppExpenditure = (select IYMAnalysisSet.Actual from IYMAnalysisSet where IYMAnalysisSet.IYMAnalysis_Programmes = ProgrammesSet.Number) where exists (select * from IYMAnalysisSet where IYMAnalysisSet.IYMAnalysis_Programmes = ProgrammesSet.Number)")

ProgrammesSet is related to IYMAnalysis set by IYMAnalysis_Programmes = Number. So this updates the ppBudget and ppExpenditure columns in ProgrammesSet based on Projections and Action from the IYMAnalysisSet table.
 
Top