I have an ArrayList of Strings, which is constantly changed (adding and removing lines) by a non-UI thread. In the UI I want to show the current content of that ArrayList in a simple TextView.
When preparing the text for the TextView by joinToString("\n"), I was immediately receiving a ConcurrentModificationException, which was not very surprising.
So, to avoid that, I cloned the ArrayList, before joining it to a String:
val textLines = globalTextLineArray.clone() as ArrayList<String>
myTextView.text = textLines.joinToString("\n")
What I am not understanding is, that even now I am receiving from time to time a ConcurrentModificationException.
How can that happen?
The StackTrace is:
java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.next(ArrayList.java:866)
at kotlin.collections.CollectionsKt___CollectionsKt.joinTo(_Collections.kt:3341)
at kotlin.collections.CollectionsKt___CollectionsKt.joinToString(_Collections.kt:3361)
at kotlin.collections.CollectionsKt___CollectionsKt.joinToString$default(_Collections.kt:3360)
at MyActivity.updateTextInView(MyActivity.kt:79)
at MyActivity.access$updateTextInView(MyActivity.kt:24)
at MyActivity$textViewUpdater$1.run(MyActivity.kt:85)
at android.os.Handler.handleCallback(Handler.java:789)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6944)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
There may be better ways to achieve what I am trying to do (e.g. using a thread-safe collection). But still I would like to understand, why the cloning attempt does not work.