Android Question Crash when trying to iterate through a map and using map.remove

netchicken

Active Member
Licensed User
Longtime User
I am iterating with a for loop through a map of phone details and removing those older than 14 days. However unless I use a try catch the loop crashes, I assume its because I am reducing the amount of items in the map and then it dies when trying to count to the original number of items.

Is there any way around this without resorting to a try catch?

B4X:
For I = 0 To phoneMap.Size - 1
       
        'get the key out
        Dim Key As String= phoneMap.GetKeyAt(I)
        Dim  Value As String= phoneMap.GetValueAt(I)
        Log("read for date " & Value)

        Dim comma As Int = Value.IndexOf(",")
        Dim dateSaved  As String = Value.SubString(comma +1)
        'PROBLEM! You have a loop through a list but the list is shrinking as items are deleted from it, therefore you run out of items and the system crashes, ie: it wants to loop to 14 but you only have 7 in the list because you have just deleted out 7. fixed with below sort of
       
    Try  'nasty coding but wtf
        If (dateSaved <= date14DaysAgo) Then
                Log(" delete this entry too old " & dateSaved)
                phoneMap.Remove(Key)
        End If
    Catch
    End Try
Next
 

netchicken

Active Member
Licensed User
Longtime User
Solved it with a list in its own loop. So pass items to be deleted to a list then loop the list and delete the items from there.

B4X:
For i = PhoneMap.Size - 1  To 0 Step -1
     
'... lots of code deleted here

    Dim ThirtyMins As Long = 1000 * 60 * 30

            If (datediff > ThirtyMins) Then
             
                   'pass it to a list first
                DeletesFromPhoneMap.Add(Key)
        End If

Next
'delete from the list
For i = 0 To DeletesFromPhoneMap.Size - 1
Dim key As String
Key = DeletesFromPhoneMap.Get(i)
PhoneMap.remove(Key)
Log("Delete from list "  & Key )
Next
 
Last edited:
Upvote 0
Top