This is the hoary old problem of iterating and deleting from a collection.
Erel may or may not consider this a bug!
Intuitively I expect the following to work on a Map but it errors with a NoSuchElementException.
I assume because B4A Map is not a pure Map but has some internal indexing code.
B4X:
Dim ViewsMap As Map
...
For Each dv As DraggableView In ViewsMap.keys
Dim v As View
v = dv.dView
v.RemoveView
ViewsMap.Remove(dv)
Next
Dim ViewsMap As Map
For Each dv As View In ViewsMap.keys
If dv Is DraggableView Then
Dim v As View
v = dv.dView
v.RemoveView
ViewsMap.Remove(dv)
End If
Next
Nope - that's nothing to do with the problem. All the keys are DraggableViews. The problem is an interaction between the compiled code, which produces a Java for(...) loop with a fixed number of iterations and some internal indexing added to the B4A Map. For reference the answer in this case is to clear the Map outside the loop, but there may be occasions when you want to keep some items.
B4X:
For Each dv As DraggableView In ViewsMap.keys
Dim v As View
v = dv.dView
v.RemoveView
Next
ViewsMap.Clear
OK. I guess then if you want to delete only some items in a collection you would need to copy the ones to keep to a new Map and assign it to the old variable after the loop. Or do you have a better idea?
Dim KeysToRemove As List
KeysToRemove.Initialize
For Each Key As Something In Map.Keys
If <some condition> Then KeysToRemove.Add(Key)
Next
For Each Key As Something In KeysToRemove
Map.Remove(Key)
Next