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

mxml picture mxml · Aug 16, 2016 · Viewed 71k times · Source

I have this firebase database

enter image description here

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

Every user is added as an object with user-ID as a name of that object, I need to retrieve this objects without knowing that user-ID

I searched the documentation , it's related to DataSnapshot but i couldn't get a DataSnapshot without a listener ! is it correct to seek a DataSnapshout or shall i use something else

Answer

Ryan Pierce picture Ryan Pierce · Aug 16, 2016

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<String,Object>) 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<String,Object> users) {

    ArrayList<Long> phoneNumbers = new ArrayList<>();

    //iterate through each user, ignoring their UID
    for (Map.Entry<String, Object> 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.