3

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. 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.

DaveyDaveDave
  • 9,821
  • 11
  • 64
  • 77
MARSH
  • 117
  • 1
  • 7
  • 22
  • While iterating over a list using iterator, you cannot modify the list directly. I would suggest to go for plain old for loop. for (int i = 0; i < list.size; i++) and do your modification – Nishit Apr 05 '18 at 05:19

2 Answers2

0

Check if you are modifying same collection while traversing using for each. If you want to modified same collection you need to use iterator.

Krunal Dave
  • 113
  • 8
-2
 val tempList = arrayListOf<MyObject>()
    tempList.addAll(currentList)
    currentList.forEach {
        if (condition to remove here) {
            tempList.remove(it)
        }
    }
currentList = tempList
roque
  • 101
  • 2
  • 3
    Welcome to StackOverflow! :) It is advisable that you always explain at least a little about your code. – Ray Aug 23 '18 at 09:40