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 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
With Firebase database queries, you can selectively retrieve data based on various factors. To construct a query in your database, you start by specifying how you want your data to be ordered using one of the ordering functions: orderByChild() , orderByKey() , or orderByValue() .
To read data at a path and to listen for any changes if the data changes, we have to use the addValueEventListener() or addListenerForSingleValueEvent() method to add a ValueEventListener to a database reference. These two methods will add a valueEventListener to a DatabaseReference.
We can filter data in one of three ways: by child key, by key, or by value. A query starts with one of these parameters, and then must be combined with one or more of the following parameters: startAt , endAt , limitToFirst , limitToLast , or equalTo .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With