Android Code Snippet Running totals with a Map

ClassName: MapCount

Description: Based on @Erels code in another post (here) keep a running total of as many items as you want while parsing any data.

B4X:
'Class module
Private Sub Class_Globals
    Private CountMap As Map
    Private mName As String
End Sub

'Initializes the object. You can add parameters to this method if needed.
Public Sub Initialize(Name As String)
    CountMap.Initialize
    mName = Name
End Sub

Sub Update(Source As Object)
    CountMap.Put(Source,CountMap.GetDefault(Source,0)+1)
End Sub

Sub LogOutput
    Log(" ")
    LogColor("Output for MapCount: " & mName,Colors.Blue)
    Dim Count As Int = 0
    For Each Key As Object In CountMap.Keys
        Log(Key&" "&CountMap.Get(Key))
        Count=Count+CountMap.Get(Key)
    Next
    Log("Total Count = "&Count)
    LogColor("End of Output for MapCount: " & mName,Colors.Blue)
    Log(" ")
End Sub

Sub LogOutputHex

    'Create the Formatter Object
    Dim Format As JavaObject
    Format.InitializeStatic("java.lang.String")

    Dim FormatString As String = "%#4X"
    Log(" ")
    LogColor("Output for MapCount: " & mName,Colors.Blue)
    Dim Count As Int = 0
    For Each Key As Object In CountMap.KeyS
        Try
           Dim KeyStr As String = Format.RunMethod("format",Array As Object(FormatString,Array As Object(Key)))
           Log(KeyStr&" "&CountMap.Get(Key))
           Count=Count+CountMap.Get(Key)
        Catch
            LogColor("Could not parse " & Key & " as Hex - it's count is: ",Colors.Red)
            Log(Key&" "&CountMap.Get(Key))
            Count=Count+CountMap.Get(Key)
        End Try
    Next
    Log("Total Count = "&Count)
    LogColor("End of Output for MapCount: " & mName,Colors.Blue)
    Log(" ")
End Sub

Sub GetCount(Key As Object)
    Return CountMap.GetDefault(Key,0)
End Sub

Dependencies: None

Example usage:

B4X:
Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
    Dim MC As MapCount
End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.

End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    'Activity.LoadLayout("Layout1")
    MC.Initialize
End Sub

Sub Activity_Resume

    Dim Test() As String = Array As String("First","Second","Third","First","Fourth","Fifth","Second","First","Second","Fourth","First","Fourth","First","Fourth","First","First")
    For Each Item As String In Test
        MC.Update(Item)
    Next

    MC.LogOutput
End Sub

Tags: Map Running Total Count Items Hex
 
Last edited:

stevel05

Expert
Licensed User
Longtime User
Updated code to take a name parameter to print in the log, also display the key values as Hex using code from the Format String snippet.
 
Top