Reputation: 145
I am trying to download data from Firestore and add it to a POJO class but when I use to add all functions all the previous elements are removed from the list only one element remains every time I want to append values into the list.
My Code:
db.collection("Posts").document(postId).collection("Groups")
.get()
.addOnSuccessListener { result ->
for (document in result) {
Log.d(myTAG, "${document.id} => ${document.data}")
arr.add(document.id)
Log.d(myTAG, "Documents are $document")
db.collection("Users")
.whereEqualTo("id", document.id)
.get()
.addOnCompleteListener {
if (it.isSuccessful){
val objects2: List<Users> = it.result?.toObjects(Users::class.java) as List<Users>
val list2 = mutableListOf<Users>()
list2.addAll(objects2)
userList.value = list2
Log.d(myTAG," list size "+ list2.size.toString())
}
}
}
}
.addOnFailureListener { exception ->
Log.d(myTAG, "Error getting documents: ", exception)
}
Upvotes: 0
Views: 77
Reputation: 138824
when I use add all function all the previous elements are removed from the list only one element remains every time
This is happening because are creating a new mutable list at every iteration in your for-loop. You should only create a single instance. So to solve this, please move the following line of code:
val list2 = mutableListOf<Users>()
Right before the line where the for-loop starts:
for (document in result) { ... }
Upvotes: 2