简体   繁体   中英

How to get key from Firebase Database?

This is my Database Structure在此处输入图像描述

I wanna know how can I get the key that has been marked in the image.

I try to use this code to fetch the Key.

mDatabase = FirebaseDatabase.getInstance().getReference();
        mDatabase.child("Admin Order")
                .orderByChild("userId")
                .equalTo(userID)
                .addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
                            orderId = childSnapshot.getKey();
                        }
                    }

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

                    }
                });

But when I use debugger to check the Value of key it is showing null 在此处输入图像描述

As you can see above it is showing orderId = null . Can anyone help?

I replicated your data and tried removing .orderByChild("userId").equalTo(userID) and I am able to get the keys

mDatabase = FirebaseDatabase.getInstance().getReference();
        mDatabase.child("Admin Order")
                .addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
                            orderId = childSnapshot.getKey();
                            // you can order by here once u have keys
                        }
                    }

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

                    }
                });

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