Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
}

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading