Issue
I have a list of accounts, and when i make the long click, I want to remove the item from the arraylist. I'm trying to remove it from a alertdialog, but i'm getting the ConcurrentModificationException. This is where is crashing:
listAccounts.forEachIndexed { index, account ->
if (idParamether == account.id) {
listAccounts.remove(account)
}
}
Solution
That's a common problem with the JVM, if you want to remove an item from a collection while iterating through it, you need to use the Iterators
exemple:
val myCollection = mutableListOf(1,2,3,4)
val iterator = myCollection.iterator()
while(iterator.hasNext()){
val item = iterator.next()
if(item == 3){
iterator.remove()
}
}
this will avoid ConcurrentModificationExceptions
I hope this answered your question, have a good day
Edit: you can find another explanation here, even if it is Java code the problem is the same
Edit n°2 the anwser of leonardkraemer show you a more kotlin-friendly way to do so
Answered By - SeekDaSky
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.