简体   繁体   中英

Trying To Get Key From a Child Value In Firebase Database

I Have String From Which I am Trying To Get The Key So I Can Use That Key To retrive Some More Value At That Key Location. This Is My Query Code -

private void xyz()
{
    Query t1 = FirebaseDatabase.getInstance().getReference().child("leaderboard").child(matchnumber).child(conlocation).orderByChild("teamname").equalTo(name1);
    t1.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            String key = dataSnapshot.getKey();
            Toast.makeText(Leaderboard.this, key, Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}

This is My Database Data Structure.

在此处输入图像描述

So I Am Trying To Get The Key 1,2,3,4 But I am Getting Contest1 As a Key.

How about loop through the children:

......
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

for(DataSnapshot ds: dataSnapshot.getChildren()){
//this runs for every key
String key = ds.getKey();
Toast.makeText(Leaderboard.this, key, Toast.LENGTH_SHORT).show();
}

}

......

For the comment:

.........

for(DataSnapshot ds: dataSnapshot.getChildren()){
//this runs for every key
String key = ds.getKey();
sendKey(key);
........


//new method under your private method
public void sendKey(String key){

//do what ever with the key or keys


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM