'Looping through nodes from Firebase Real-time database in Android Studio with Kotlin
Working with Android Studio and firebase the link below shows the structure of our database.
Also added copy-pasted how the json file of the structure looks like.
https://i.stack.imgur.com/X3vkz.png
"Events" : {
"-MxoB2kU8Okx0gFbnEIx" : {
"addGoogleMaps" : true,
"address" : "Gjuterivägen 3",
"bringAlcohol" : false,
"date" : "WEDNESDAY 23 FEBRUARY 2022",
"description" : "Fest på holma",
"endTime" : "End Time: 22:15",
"maxAttendees" : 6,
"overallsOn" : true,
"ownerEmail" : "[email protected]",
"plusOne" : false,
"startTime" : "Start Time: 06:15",
"title" : "Fest hos Mange"
},
Eventually there would be 50 events like this up in the database at the same time and what I need to do is loop through them all, without knowing their node-name and collect what i need.
Question:
With Kotlin, how can I access each child in Events without using their String path in a loop and take the following variables from each individual child:
Title, Location, and Date.
With these I need to instantiate an object that would represent that child and then put it in :
private val events = mutableListOf<Event>()?
I edited the entire question and I hope this is more understandable than previous time. Thanks!
Solution 1:[1]
Have you tried something like this:
mDatabase.child("Events").get().addOnSuccessListener {
Log.i("firebase", "Got events: ${it}")
}.addOnFailureListener{
Log.e("firebase", "Error getting data", it)
}
Generally it is recommended to use ValueEventListener instead of get() though: https://firebase.google.com/docs/database/android/read-and-write#read_data_once
Solution 2:[2]
Thanks to Frank Van Puffelen(in a comment) linked something very useful which seems to work the way I want!
https://firebase.google.com/docs/database/android/lists-of-data#read_and_write_lists
Here is the solution:
val database = FirebaseDatabase.getInstance().getReference("Events")
database.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
for (postSnapshot in dataSnapshot.children) {
println(postSnapshot.child("title").value)
//Here i can just get what ever variable i need with the line above.
}
}
override fun onCancelled(databaseError: DatabaseError) {
// Getting Post failed, log a message
Log.w(TAG, "loadPost:onCancelled", databaseError.toException())
// ...
}
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Klemens Zleptnig |
| Solution 2 | Christoffer Kvist |
