ConcurrentModificationException when trying initialize ArrayList's items with their listenners

64 Views Asked by At

I got ConcurrentModificationException when trying initialize a ArrayList<CheckBox> as blow:

     late init var checkBoxArrayList = ArrayList<CheckBox>()
     val repeatDays: List<Int> = getRepeatDays() // List of the order of days of the week starts from 1 (monday)
     
    
     checkBoxArrayList = arrayListOf(
        checkBoxMon.apply { this.isChecked = false
            this.setOnCheckedChangeListener(this@RepeatOptionsFragment)},
        checkBoxTue.apply { this.isChecked = false
            this.setOnCheckedChangeListener(this@RepeatOptionsFragment)},
        checkBoxWed.apply { this.isChecked = false
            this.setOnCheckedChangeListener(this@RepeatOptionsFragment)},
        checkBoxThu.apply { this.isChecked = false
            this.setOnCheckedChangeListener(this@RepeatOptionsFragment)},
        checkBoxFri.apply { this.isChecked = false
            this.setOnCheckedChangeListener(this@RepeatOptionsFragment)},
        checkBoxSat.apply { this.isChecked = false
            this.setOnCheckedChangeListener(this@RepeatOptionsFragment)},
        checkBoxSun.apply { this.isChecked = false
            this.setOnCheckedChangeListener(this@RepeatOptionsFragment)}
    )
    repeatDays?.forEach { day ->
        // The checkBoxArrayList starts from index 0 (for monday), while the DayOfWeek enum assigns monday to 1.
        checkBoxArrayList[day - 1].isChecked = true

    }

But when I change the code as below, this issue is gone. I don't understand how the setOnCheckedChangeListener() impact and cause the error?. Could you give me an explanation.

    checkBoxArrayList = arrayListOf(
        checkBoxMon.apply { this.isChecked = false },
        checkBoxTue.apply { this.isChecked = false },
        checkBoxWed.apply { this.isChecked = false },
        checkBoxThu.apply { this.isChecked = false },
        checkBoxFri.apply { this.isChecked = false },
        checkBoxSat.apply { this.isChecked = false },
        checkBoxSun.apply { this.isChecked = false }
    )

    repeatDays?.forEach { day ->
        checkBoxArrayList[day - 1].isChecked = true

    }

    checkBoxArrayList.forEach {
        it.setOnCheckedChangeListener(this)
    }
0

There are 0 best solutions below