I am having some problems with Firebase and Kotlin for loop.
See the scenario below.
- I have a list of classes of a school (have already in a variable from another source)
- There several sections for each of the classes in the Firebase Realtime Database
- I want to get all the sections from the database for the class list
- Finally I want to show the section list as a dialog
Here is a sample code
private val firebaseDB = Firebase.database.reference
private val clazzList: ArrayList<Clazz> = ArrayList()
private fun getSections() {
val sectionList: ArrayList<Section> = ArrayList()
for (clazz in clazzList) {
firebaseDB.child("schools").child("sections")
.orderByChild("classNodeKey")
.equalTo(clazz.nodeKey)
.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onCancelled(p0: DatabaseError) {}
override fun onDataChange(p0: DataSnapshot) {
if (p0.exists()) {
val hashDataArray: ArrayList<HashMap<*, *>> = ArrayList()
for (datasnapshot in p0.children) {
hashDataArray.add(datasnapshot.value as java.util.HashMap<*, *>)
}
for (hashData in hashDataArray) {
val sectionObject = Gson().fromJson(Gson().toJsonTree(hashData), Section::class.java) as Section
sectionList.add(sectionObject)
}
}
}
})
}
showSections(sectionList) // Show the section list in a dialog. It is being called before the completion of for-loop above.
}
private fun showSections(sectionList: ArrayList<Section>) {
MaterialDialog(this).show {
title(text = "Sections")
listItemsSingleChoice(items = sectionList)
positiveButton(text = "OK")
}
}
Here is the data model class Clazz.kt
data class Clazz (val nodeKey: String, val name: String)
Here everything is working fine except one thing and that is The method showSections(sectionList: ArrayList) is being executed before the completion of for-loop and the dialog is showing an empty list
But I want to first complete the for-loop and then want to show the dialog. How can I achieve this?