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:

Mashiane

Expert
Licensed User
Longtime User
Hi @Informatix

Someone said to me asking questions when you don't understand is not a sign of weakness but a sign of wisdom. I hope people will bear with me asking so many questions. :). As a newbie in b4x, I'm grateful that there are people like you with both experience and the know how and are willingness to help other coders like me. Viva @Informatix!

I hear your explanation and it makes sense. Thanks again.
 

Mashiane

Expert
Licensed User
Longtime User
B4X:
'Description: VB equivalent LTrim method using Regular Expressions
'Tag: LTrim, Regular Expressions
Sub LTrim(s As String) As String
   Dim m As Matcher = Regex.Matcher("^(\s+)", s)
   If m.Find Then
     Return s.SubString(m.GetEnd(1))
   Else
     Return s
   End If
End Sub

'Description: VB equivalent RTrim method using Regular Expressions
'Tag: RTrim, Regular Expressions
Sub RTrim(s As String) As String
   Dim m As Matcher = Regex.Matcher("(\s+)$", s)
   If m.Find Then
     Return s.SubString(m.GetEnd(1))
   Else
     Return s
   End If
End Sub
 

Mashiane

Expert
Licensed User
Longtime User
B4X:
'Description: Function to customize your button with backcolor, textcolor, bordercolor, bordersize and radius
'Tag: button, backcolor, textcolor, radius
Sub Fancy_Button(btn As Button, backColor As Int, textColor As Int, borderSize As Int, cornerRadius As Float, borderColor As Int)
    Dim dr As ColorDrawable
    dr.Initialize2(backColor, cornerRadius, borderSize, borderColor)
    btn.Background = dr
    btn.TextColor = textColor
    btn.Invalidate
End Sub

'Description: BoosStrap default button
Sub BS_ButtonDefault(btn As Button)
    Fancy_Button(btn,Colors.White,Colors.Black,1,2%x,Colors.Gray)
End Sub

'Description: BoosStrap primary button
Sub BS_ButtonPrimary(btn As Button)
    Dim col As Int = Colors.RGB(51,122,183)
    Fancy_Button(btn,col,Colors.white,1,2%x,col)
End Sub

'Description: BoosStrap success button
Sub BS_ButtonSuccess(btn As Button)
    Dim col As Int = Colors.RGB(68,157,68)
    Fancy_Button(btn,col,Colors.white,1,2%x,col)
End Sub

'Description: BoosStrap info button
Sub BS_ButtonInfo(btn As Button)
    Dim col As Int = Colors.RGB(91,192,22)
    Fancy_Button(btn,col,Colors.white,1,2%x,col)
End Sub

'Description: BoosStrap warning button
Sub BS_ButtonWarning(btn As Button)
    Dim col As Int = Colors.RGB(240,173,78)
    Fancy_Button(btn,col,Colors.white,1,2%x,col)
End Sub

'Description: BoosStrap warning button
Sub BS_ButtonDanger(btn As Button)
    Dim col As Int = Colors.RGB(217,83,79)
    Fancy_Button(btn,col,Colors.white,1,2%x,col)
End Sub
 

Mashiane

Expert
Licensed User
Longtime User
B4X:
'Description: Returns map keys as a delimited string
'Tag: map, delimiter, string
Sub MapKeysToMV(m As Map, Delim As String) As String
    Dim sb As StringBuilder
    sb.Initialize
    For Each k As String In m.Keys
        sb.Append(k).Append(Delim)
    Next
    Return RemDelim(sb.tostring,Delim)
End Sub
 

Mashiane

Expert
Licensed User
Longtime User
B4X:
'Description: Return the mobile number of your device using Reflection
'Tag: mobile number
Sub Phone_GetMobileNumber1() As String
    Dim Obj1 As Reflector
     Dim LineNumber As String
     Obj1.Target = Obj1.GetContext
     Obj1.Target = Obj1.RunMethod2("getSystemService", "phone", "java.lang.String")
     LineNumber = Obj1.RunMethod ("getLine1Number")
    Return LineNumber
End Sub
 

Mashiane

Expert
Licensed User
Longtime User
B4X:
'Description: Remove an item from a customlistview using its value
'Tag: customlistview, remove item
Sub ListViewRemoveItemByValue(lstView As CustomListView, Value As String)
    Dim lstTot As Int
    Dim lstCnt As Int
    Dim lstStr As String
    lstTot = lstView.GetSize - 1
    For lstCnt = lstTot To 0 Step -1
        lstStr = lstView.GetValue(lstCnt)
        Select Case lstStr
        Case Value
            lstView.RemoveAt(lstCnt)
            Exit
        End Select
    Next
End Sub
 

Mashiane

Expert
Licensed User
Longtime User
Just found this lovely code...
B4X:
'Description: Make an imageview to have rounded corners
' Tag: imageview, rounded corners
Sub ImageView_SetRoundCorners(img As ImageView, imgDir As String, imgPath As String, imgRadius As Int)
    Dim b As Bitmap
      Dim rsie As RSImageEffects
      Dim rsip As RSImageProcessing
    rsip.Initialize
    b = LoadBitmapSample(imgDir, imgPath,100%x, 100%y)
    b = rsip.createScaledBitmap(b, img.width, img.height, False) ' createScaledBitmap seems to produce a better compressed image
    img.Bitmap = rsie.RoundCorner(b, imgRadius) ' round bitmap corners
End Sub

Uses: https://www.b4x.com/android/forum/threads/rsimageprocessing-library.16230/
 

Mashiane

Expert
Licensed User
Longtime User
B4X:
'Description: Sort a map by its keys in ascending order
'Tag: map, sort, asc
Sub SortMapKeys (m As Map, SortAsc As Boolean)
   Private KeysList As List
   Private m2 As Map
   Private key As String
   Private mVal As Object
   Private i As Int
   KeysList.Initialize
   m2.Initialize
  
   ' get all the keys
   KeysList = m.Keys
   KeysList.Sort(True)
  
   For i= 0 To KeysList.Size - 1
       key = KeysList.Get(i)
    mVal = m.Get(key)
    m2.Put(key, mVal)
   Next
  m.Clear
  For Each m2Key As String In m2.Keys
      m.Put(m2Key, m2.Get(m2Key))
  Next
End Sub
 

Mashiane

Expert
Licensed User
Longtime User
B4X:
'Description: Calculate the age of the person at death
'Tag: age, date, death
Sub AgeAtDeath(birthDate As String, deathDate As String) As String
    DateTime.DateFormat = "yyyy-MM-dd"
    Dim Datestart As Long
    Dim DateEnd As Long
    Dim age As String
    Datestart = DateTime.DateParse(birthDate)
    DateEnd = DateTime.DateParse(deathDate)
    Dim p As Period
    p = DateUtils.PeriodBetween(Datestart,DateEnd)
    age = p.Years &" Years, " & p.Months & " months, " & p.Days & " days"
    Return age
End Sub
 

Mark Zraik

Member
Licensed User
Longtime User
Mashiane, your work and others is not wasted. Thank you for putting this together. Thank you to Informatix and others for chiming in and showing better or different ways to get the job done. As we jump from one thing to another in life, it helps to have a collection to at least start from. Thank you!!
 

Ferbis

Active Member
Licensed User
Longtime User
Same opinion as Mark. Thanks Mashiane for your time and work putting all this code routines together; and also thanks to Informatix and others for being there.
 
Last edited:
Top