Gino Sesia
Gino Sesia

Reputation: 393

how do i retrieve data from firebase realtime database using kotlin

Im trying to pull data from firebase realtime database but i'm not sure how to pull more than one data piece at the same time if its possible.

so this is what the database looks like: enter image description here

so far i have managed to be able to print out all of these values in the following way:

private fun getData() {

    var currentUid = mAuth.currentUser?.uid
    val myRef = database.getReference("User-following").child(currentUid!!)

    myRef.addValueEventListener(object : ValueEventListener {
        override fun onDataChange(dataSnapshot: DataSnapshot) {
            val children = dataSnapshot.value


            Log.e("Database", "value = $children")
        }

        override fun onCancelled(error: DatabaseError) {
            Log.e("Database", error.toString())
        }
    })
}

when it prints the value of children i get all 5 in the following format:

E/Database: value = {-MLwcu81dicGo1NezqJD=1, -MLwcwBjdjRo-vgSkEjR=1, -MLwep1w5z4DfGeabx0d=1, -MLw_sc6aHPxPpGBIpCL=1, -MLwdqVch3iDr3GXylln=1}

how to i return each individual id so that i can use it to retrieve the data that corresponds to each id?

Upvotes: 0

Views: 577

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 598728

To access the individual child nodes under the snapshot you retrieved, you'll want to loop over its children.

override fun onDataChange(dataSnapshot: DataSnapshot) {
    for (childSnapshot in dataSnapshot.children) {
        Log.i("Database", "child key = $childSnapshot.key")
    }
}

Also see the Firebase documentation on listening to value events.

Upvotes: 2

Related Questions