Android Question How to use IndexOf in a list of Map

asales

Well-Known Member
Licensed User
I have this type:
B4X:
Type Events (EventName As String, EventDate As Long)
and use this code to populate the map and insert in a list:

B4X:
Dim NewList As List
NewList.Initialize

Dim dt As Event : dt.Initialize
dt.EventDate = DateTime.DateParse(12 & "/" & 25 & "/" & 2015)
dt.EventName = "Christmas"
NewList.Add(dt)

Dim dt As Event : dt.Initialize
dt.EventDate = DateTime.DateParse(1 & "/" & 1 & "/" & 2015)
dt.EventName = "New Year"
NewList.Add(dt)
but I don't know how to use IndexOf to check if value exists and retrieve the EventName.

I tried to make this, but don't works:

B4X:
Dim newDate As Long = DateTime.DateParse(12 & "/" & 25 & "/" & 2015)
Dim f As Int
f = NewList.IndexOf(newDate)
If f > -1 Then
    Log("Christmas Found")
End If
it's possible to use the IndexOf in a List with Map to find directly the item?

Thanks in advance for any tip.
 

sorex

Expert
Licensed User
you could try this

B4X:
Dim newDate As Long = DateTime.DateParse(12 & "/" & 25 & "/" & 2015)

If listSearch(NewList,newDate)=True Then
    Log("Christmas Found")
End If
End Sub

Sub listSearch(l As List,s As String)
Dim e As Events
For x=0 To l.Size-1
    e=l.Get(x)
    If e.EventDate=s Then Return True
Next
Return False
End Sub
 

stevel05

Expert
Licensed User
You are not using a Map, but a type. If you only have one field to store, you could use a Map directly instead of the Type:

B4X:
    Dim DateMap As Map
    DateMap.Initialize

    Dim Date As Long = DateTime.DateParse(12 & "/" & 25 & "/" & 2015)
    DateMap.Put(Date,"Christmas")

    Date = DateTime.DateParse(1 & "/" & 1 & "/" & 2015)
    DateMap.Put(Date,"New Year")

    Dim newDate As Long = DateTime.DateParse(12 & "/" & 25 & "/" & 2015)

    Dim EventName As String = DateMap.GetDefault(newDate,"NF")
    If EventName <> "NF" Then
        Log(EventName & " Found")
    End If
If you have more fields, then you can store a Type object within the Map and still reference the date in the same way. It depends on exactly you want to store, you can only have unique keys in a map, so you won't be able to do it this way if you will have multiple events on the same day, unless you build it into a Type with a List.
 
Top