Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get child key in Firebase Realtimedatabase

I’m trying to paging realtime databse , and my database structure looks like this.

{ 
  "dinosaurs":{
    "lambeosaurus": {
      "UID1_1sajdslkjzxdq2311a":{
        "height" : 5.1,
        "length" : 12.5,
        "weight": 3211
      },
       "UID2_2cxzcxczz34zz":{
        "height" : 2.7,
        "length" : 11.5,
        "weight": 5000
      },
    //..

    }
  }
}

The key what I want to get is "UID1_1sa...".
I tried with code below.

val DBreference = mydb.reference.child("dinosaurs").child("lambeosaurus")
val FirstKey = DBreference.orderByChild("height").limitToFirst(1).get().await().key 
Log.d("FirstKey ","${FirstKey}")

but it returns "lambeosaurus" not "UID1_1sa~..".
How can I get "UID1_1sa~.."?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thank you.

*Edit

I changed code into

    val FirstKey = DBreference.orderByChild("height")
         .limitToFirst(1).get().await().children.first().key

It returns "UID1_1sa..." as I want.

>Solution :

Try below code

val DBreference = FirebaseDatabase.getInstance().getReference()
val usersRef: DatabaseReference = rootRef.child("dinosaurs")
val valueEventListener: ValueEventListener = object : ValueEventListener() {
    fun onDataChange(dataSnapshot: DataSnapshot) {
        for (ds in dataSnapshot.getChildren()) {
            val firstKey: `val` = ds.getKey()
            Log.d("TAG-firstKey ", firstKey)
        }
    }

    fun onCancelled(databaseError: DatabaseError?) {}
}
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading