How to get all child's data in firebase database?

后端 未结 2 1446
南笙
南笙 2020-11-28 05:26

I have this firebase database

and i need to get all phone numbers of users , which listener shall i use to get all childes?

Every user is added as

2条回答
  •  攒了一身酷
    2020-11-28 05:58

    First retrieve your users datasnapshot.

    //Get datasnapshot at your "users" root node
        DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users");
        ref.addListenerForSingleValueEvent(
                new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                        //Get map of users in datasnapshot
                        collectPhoneNumbers((Map) dataSnapshot.getValue());
                    }
    
                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                        //handle databaseError
                    }
                });
    

    Then loop through users, accessing their map and collecting the phone field.

    private void collectPhoneNumbers(Map users) {
    
        ArrayList phoneNumbers = new ArrayList<>();
    
        //iterate through each user, ignoring their UID
        for (Map.Entry entry : users.entrySet()){
    
            //Get user map
            Map singleUser = (Map) entry.getValue();
            //Get phone field and append to list
            phoneNumbers.add((Long) singleUser.get("phone"));
        }
    
        System.out.println(phoneNumbers.toString());
    }
    

    This listener will only retrieve the datasnapshot when explicitly called. Consider storing a list of numbers under an "allPhoneNumbers" node in addition to your users node. This will make your datasnapshots lighter and easier to process when collecting all numbers. If you have say hundreds of users, the "users" datasnapshot will be way too big and the "allPhoneNumbers" list will be far more efficient.

    The above code was tested on your sample database and does work. However, your phone field may need to be casted to String or int depending on your user's phone instance field's type.

提交回复
热议问题