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
B4X:
'Description: find a panel imageview using its tag property
'Tag: label, text, tag
Sub FindPanelImageViewByTag(pnl As Panel, imgTag As String) As ImageView
    Return FindViewByTag(pnl, imgTag)
End Sub

'Description: find any view by its tag property
'Tag: view, search, find, tag
Sub FindViewByTag(Parent As Panel, Name As String) As View
For Each v As View In Parent.GetAllViewsRecursive
     If Name = v.Tag Then Return v
Next
Return Null
End Sub
 

Informatix

Expert
Licensed User
Longtime User
B4X:
'Description: set the text value of a panel label using its tag property
'Tag: label, text, tag
Sub SetPanelImageViewByTag(pnl As Panel, imgTag As String, imgPath As String, imgName As String)
    For Each v As View In pnl.GetAllViewsRecursive
        If v Is ImageView Then
            If LCase(v.tag) = LCase(imgTag) Then
                Dim img As ImageView
                img = v
                img.Bitmap = LoadBitmap(imgPath, imgName)
            End If
        End If
    Next
End Sub
Note that the use of LoadBitmap is strongly discouraged as it uses a lot more memory than needed in some cases. LoadBitmapSample should always be used instead.
Much better: my AcceleratedSurface library provides a LoadScaledBitmap function that uses even less memory and fix the issues with density of LoadBitmapSample.
 

Mashiane

Expert
Licensed User
Longtime User
Note that the use of LoadBitmap is strongly discouraged as it uses a lot more memory than needed in some cases. LoadBitmapSample should always be used instead.
Much better: my AcceleratedSurface library provides a LoadScaledBitmap function that uses even less memory and fix the issues with density of LoadBitmapSample.

Wow, I like, I will check it out. My current app uses a lot of bitmaps and this will be very useful. Ta!
 

Mashiane

Expert
Licensed User
Longtime User
B4X:
'Description: Get the version name of your app (Main > VersionName)
'Tag: app version name
Sub GetVersionName() As String
    Dim pm As PackageManager
    Dim packageName As String
    packageName = GetPackageName
    Dim AppVersion As String
    AppVersion = pm.GetVersionName(packageName)
    Return AppVersion
End Sub
 

Mashiane

Expert
Licensed User
Longtime User
B4X:
'Description: Get the version code of your app (Main > VersionCode)
'Tag: app, version code
Sub GetVersionCode() As Int
    Dim pm As PackageManager
    Dim packageName As String
    packageName = GetPackageName
    Dim AppVersion As String
    AppVersion = pm.GetVersionCode(packageName)
    Return AppVersion
End Sub
 

Informatix

Expert
Licensed User
Longtime User
B4X:
'Description: Get the version name of your app (Main > VersionName)
'Tag: app version name
Sub GetVersionName() As String
    Dim pm As PackageManager
    Dim packageName As String
    packageName = GetPackageName
    Dim AppVersion As String
    AppVersion = pm.GetVersionName(packageName)
    Return AppVersion
End Sub
Same as above. Application.VersionName...
 

Mashiane

Expert
Licensed User
Longtime User
B4X:
'Description: Get the label of your application (Main > ApplicationLabel)
'Tag: application label
Sub GetApplicationLabel() As String
    Dim pm As PackageManager
    Dim packageName As String
    packageName = GetPackageName
    packageName = pm.GetApplicationLabel(packageName)
    Return packageName
End Sub
 

Mashiane

Expert
Licensed User
Longtime User
B4X:
'Description: copy all images from dirassets to specific folder
'Tag: dirassets, copy
Sub ExtractImagesFromDirAssets()
    ' get the app label
    Dim al As String = Application.LabelName
    ' create an internal folder to store the contents
    File.MakeDir(File.DirInternal, al)
    Dim fTot As Int
    Dim fCnt As Int
    Dim fStr As String
    Dim lst As List
    Dim ext As List
    Dim ext1 As String
    ext.Initialize
    ext.Add("png")
    ext.Add("jpg")
    ext.Add("gif")
    ' get all the list of files under dirassets
    lst = File.listfiles(File.DirAssets)
    fTot = lst.Size - 1
    For fCnt = 0 To fTot
        ' get the file name
        fStr = lst.Get(fCnt)
        ' get the file extension
        ext1 = GetFileExt(File.DirAssets & "/" & fStr)
        ' if this extension exists in ours, save file
        If ListItemExist(ext,ext1) = True Then
            If File.Exists(File.DirInternal, al & "/" & fStr) = False Then File.Copy(File.DirAssets, fStr, File.DirInternal, al & "/" & fStr) 
        End If
    Next
End Sub
 
Last edited:

Informatix

Expert
Licensed User
Longtime User
B4X:
' Description: Use LoadBitmap function to return an image from DirAssets
' if the image does not exist, an alternative image can be used
If the image does not exist in the assets, then just add it or don't try to access it. I don't understand the usefulness of this function. You're supposed to know what you put in your Assets folder and what is in the internal folder (nobody else but you can put things here).

And I don't really understand why you want to put all assets images in the internal folder. Reading them from the folder is slightly faster, but you have to copy them from the assets and take room on the disk. Is there a real benefit?
 

Informatix

Expert
Licensed User
Longtime User
My advice? I never advised to do that. I just gave a theoretical point of view that does not take into account the time to copy the bitmap. My advices would be to avoid LoadBitmap and to copy to DirInternalCache rather than DirInternal. But, anyway, I'd like to understand why you posted this function because, for me, it's just personal code that serves only your purpose. Why should I use it? What's the usefulness for anyone else? And I'm curious to know whether there's a benefit to copy and load a bitmap from a folder rather than decoding it from the assets. It seems to me that's slower. No?
 

Informatix

Expert
Licensed User
Longtime User
Hi @Informatix

With due respect, like I said, don't worry about it and let's just stop talking about this over and over again.

NB: For the purposes of the app I am developing, your theory proved true because I was reading my images from dirassets before and my app was very slow, now that I followed your theory, its faster and its working very fine FOR ME, just like I said before.

Thanks very much for your 'theory', please let's close this now. You've done good in my case, let's just marvel at that and leave this to and fro. Please.

In closing, my updated GetImage method is using LoadBitmapSample and not LoadBitmap anymore and after putting a time calculator on my source code to prove your theory that is in fact true that extracting images from dirassets is slower than reading them from a directory, yes, its just milliseconds, but I need those milliseconds. Ta!
Ok but don't forget that's a forum where people are free to speak and give their opinion, and that you published in a section where we share interesting code. It's not a personal repository. It is legitimate to ask the possible uses of such a code, which are not obvious in this case, and to wonder whether the implementation of an idea proved to be performant. I don't know what you understood in my posts and I really don't care now.
 

Mashiane

Expert
Licensed User
Longtime User
B4X:
'Description: Get an image from a device directory, if it does not exist
'get an alternative image from dirassets
'Tag: dirassets, image
Sub GetImageOrAlternative(original As String, alternative As String) As Bitmap
    If Len(original) > 0 Then
        If InStr(original,".") = -1 Then original = original & ".jpg"
    End If
    If Len(alternative) > 0 Then
        If InStr(alternative,".") = -1 Then alternative = alternative & ".jpg"
    End If
    ' the image is not in dirassets, find if the original exists internally
    If File.Exists(File.DirInternal, AppTitle & "/" & original) = True Then
        Return LoadBitmapSample(File.DirInternal, AppTitle & "/" & original, 100%x, 100%y)
    Else
        ' the image does not exist internally, load alternative from dirassets
        Return LoadBitmapSample(File.DirAssets, alternative, 100%x, 100%y)
    End If
End Sub
 

Informatix

Expert
Licensed User
Longtime User
Hi, what's the easiest method then to check if there is an internet connection?
It's a complicated question because the only answer that comes to mind is: it depends. For example, if you want to connect to a server, the most clever thing to do is to try to connect to that server. No need to check anything before. If you want to access internet to check whether your server is up, then you have to ping it (or any other mean to test its availability if you disabled ICMP). No need to check anything else. I tried to explain many times in this forum why pinging the Google servers (which is a common test that you will see here and there) when the application starts is stupid but obviously people do not listen so I won't try to convince you. AFAIK, no browser (Chrome, Opera, Firefox, etc.) does that. There's a case where this Google check can be useful as explained by an user on this forum who helps customers to fix their internet connection but it's not the common use.
You can have many uses of Internet: for email, for games, for video... And you don't know sometimes the Ip address of the server to reach. In this case, just call the function that enables the connection or sends/receives the data and see whether something happens. Your connection may be broken or unavailable at a given time for various reasons so you should never assume that a check at a given time means something for a later time. You can access the network at a given place and lose the connection if you move. Same thing with the public IP address. Having one does not mean that you have currently a connection to internet. It just means that you got one sometimes in the past. Your function had another problem of reliability: it did not verify whether the returned address was a valid address for internet (e.g. 192.168.0.14 is not an internet address, it's an address given by a local router, like the wifi router at home).
 
Top