What I'm doing here is getting users groups as hashmap, then getting each group's info and doing other stuff with it. But at the end of the foreach loop my "groups" list is empty. Is there anything I can do to wait for foreach loop to finish? Thank you.
db
.child("users")
.child(firebaseUser.uid)
.get()
.addOnCompleteListener { task ->
if (task.isSuccessful) {
val document = task.result
if (document != null && document.value != null) {
val groupsObject =
document.value["groups"] as HashMap<String, Boolean>
for (groupID in groupsObject.keys) {
db
.child("groups/$groupID")
.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
db
.child("users")
.child(friendID)
.get()
.addOnCompleteListener { task ->
// check for something
// add to groups list if data is OK
}
}
override fun onCancelled(error: DatabaseError) {
// TODO: ...
}
})
}
// here "groups" data is empty, because that for each loop above
// hasn't finshed yet looping, and thus my list is displayed empty
groupsAdapter = GroupsAdapter(this@GroupsActivity, groups)
recyclerView.adapter = groupsAdapter
}
}
}