How to get the key from the value in firebase

前端 未结 7 2036
挽巷
挽巷 2020-12-01 10:04

How do I get the key \"-KLpcURDV68BcbAvlPFy\" when I know the field \"name\" contains \"efg\" in the following structure in Firebase.

clubs
    -KLpcURDV68Bc         


        
7条回答
  •  不思量自难忘°
    2020-12-01 10:17

    That's because you're using a ValueEventListener. If the query matches multiple children, it returns a list of all those children. Even if there's only a single matches child, it's still a list of one. And since you're calling getKey() on that list, you get the key of the location where you ran the query.

    To get the key of the matches children, loop over the children of the snapshot:

    mDatabase.child("clubs")
             .orderByChild("name")
             .equalTo("efg")
             .addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
                String clubkey = childSnapshot.getKey();
    

    But note that if you assume that the club name is unique, you might as well store the clubs under their name and access the correct one without a query:

    mDatabase.child("clubs")
             .child("efg")
             .addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String clubkey = dataSnapshot.getKey(); // will be efg
    

提交回复
热议问题