Home > Mobile >  how can I add arrayList elements into model class arrayList in kotlin?
how can I add arrayList elements into model class arrayList in kotlin?

Time:11-21

I am trying to add elements of arrayList into model class arrayList. But at the end, all of the elements of model class becoming the last added element. what am I missing? thanks

this is model class

class ChaplainAvailableTimesModelClass(
    var time: String? = null,
    val isBooked: Boolean = false,
    val patientUid: String? = null

    ) {
}

I defined the arraylists here

private var chaplainAvailableTimes = ArrayList<ChaplainAvailableTimesModelClass>()
private var temporaryTimes= ArrayList<String>()

this is the adding part

val chaplainAvailableTimesModelClass = ChaplainAvailableTimesModelClass()
dbSaveAvailableTimes = db.collection(chaplainCollectionName).document(chaplainUserId)
for (k in 0 until temporaryTimes.size){
     chaplainAvailableTimesModelClass.time = temporaryTimes[k]
     chaplainAvailableTimes.add(chaplainAvailableTimesModelClass)
}

CodePudding user response:

The problem in your code is this:

val chaplainAvailableTimesModelClass = ChaplainAvailableTimesModelClass() /// <-----
dbSaveAvailableTimes = db.collection(chaplainCollectionName).document(chaplainUserId)
for (k in 0 until temporaryTimes.size){
     chaplainAvailableTimesModelClass.time = temporaryTimes[k]
     chaplainAvailableTimes.add(chaplainAvailableTimesModelClass)
}

You are instantiating a chaplainAvailableTimesModelClass once before the for loop and using the same instance when adding it to your arraylist. You need to create different instances of chaplainAvailableTimesModelClass per the amount (temproraryTimes.size) that you desire.

So, depending on what you want to do, it might be worthwhile to move the instantiation of the chaplainAvailableTimesModelClass inside of the for loop.

  • Related