Android Question Strange problem with a Map

LucaMs

Expert
Licensed User
Longtime User
Test project attached (its design also is strange, but it is similar to my real project).

Error occurred on line: 37 (Main)
Line 37 is an empty line.

java.util.NoSuchElementException
at java.util.LinkedHashMap$LinkedHashIterator.nextNode(LinkedHashMap.java:759)
 

Attachments

  • MapTest.zip
    8 KB · Views: 212

Erel

B4X founder
Staff member
Licensed User
Longtime User
Why? I'm using the map key. I could understand if I was using an array and a "for next" loop.
The iterator doesn't copy the list of keys so when you change the underlying data you are making it invalid.

You need to make a copy yourself:
B4X:
Dim KeysToRemove As List
KeysToRemove.Initialize
For Each Index As Int In mapX.Keys
   KeysToRemove.Add(Index)
Next
For Each k As Int In KeysToRemove
   mapX.Remove(k)
Next
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
BTW, if you switch to B4XOrderedMap from B4XCollections then you will be able to simplify it a bit:
B4X:
Dim KeysToRemove As List
KeysToRemove.Initialize
KeysToRemove.AddAll(mapX.Keys)
For Each Key As Int In KeysToRemove
   mapX.Remove(Key)
Next

It will also allow you to access elements based on an index, without using the keys for that:
B4X:
mapX.Get(mapX.Keys.Get(3)) 'get the 4th element value
 
Upvote 0
Top