[英]How to fix concurrent modification exception in Kotlin
This is my code, in which I am adding data to a list:这是我的代码,我在其中将数据添加到列表中:
fun bindProcess(listOfDocId: MutableList<String>, isActvityLogEnabled: Boolean): Observable<MutableList<SearchResultModel>> {
return Observable.create<MutableList<SearchResultModel>> {
var filteredList =CopyOnWriteArrayList<SearchResultModel>()// mutableListOf<SearchResultModel>()
val headerItem: SearchResultModel = SearchResultModel()
headerItem.type = 0
headerItem.title = context.getString(R.string.top_matches_label)
filteredList.add(headerItem)
for (row in ContSyncApplication.getContacts()) {
if (listOfDocId.contains(row.docId)) {
val myData: SearchResultModel = SearchResultModel()
myData.type = 1
myData.docId = row.docId
myData.name = row.display_name
if (!row.profile_image.isNullOrBlank()) {
myData.imagePath = row.profile_image!!
}
filteredList.add(myData)
if (isActvityLogEnabled && DatabaseQueryHelper.checkActivityLogById(row.docId)) {
val myactivityData: SearchResultModel = SearchResultModel()
myactivityData.type = 1
myactivityData.docId = row.docId
myactivityData.name = row.display_name
myactivityData.imagePath = row.profile_image ?: ""
mActvityList.add(myactivityData)
}
}
}
if (mActvityList.size > 0) {
val activityHeader: SearchResultModel = SearchResultModel()
activityHeader.type = 0
activityHeader.title = "Activity Log"
filteredList.add(activityHeader)
filteredList.addAll(mActvityList)
}
it.onNext(filteredList)
it.onComplete()
}
}
While I execute and add data in the list I am getting a ConcurrentModificationException
.当我在列表中执行和添加数据时,我得到了一个ConcurrentModificationException
。 Can anyone suggest to me how to execute the loop so that I can fix this issue?谁能建议我如何执行循环以便我可以解决这个问题? I have to search and add to the list.我必须搜索并添加到列表中。
Check if you are modifying same collection while traversing using for each
.检查您在遍历使用for each
时是否正在修改相同的集合。 If you want to modified same collection you need to use iterator
.如果你想修改同一个集合,你需要使用iterator
。
val tempList = arrayListOf<MyObject>()
tempList.addAll(currentList)
currentList.forEach {
if (condition to remove here) {
tempList.remove(it)
}
}
currentList = tempList
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.