Home > database >  How to get child key in Firebase Realtimedatabase
How to get child key in Firebase Realtimedatabase

Time:04-30

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~.."?

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.

CodePudding user response:

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?) {}
}
    
  • Related