How can I apply loop to retrieve the required data from Firebase?

3830 views java

I am trying to get data from the following collection "Buses" if say Bus_Driver=="xyz".

My Firebase test looks like this:

enter image description here

I am getting database reference with this code:

 busInfoReference= FirebaseDatabase.getInstance().getReference("Buses");

The following loop I've applied does not work correctly:

for(DataSnapshot ds : dataSnapshot.getChildren()){
            busInfo = ds.getValue(BusInforamtion.class);
            if(ds.exists()) {


How can I apply loop to get the required data? Thanks in advance.

answered question

1 Answer


To solve this, you need query your database like this:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("Buses").orderByChild("Bus_Driver").equalsTo("xyz");
ValueEventListener valueEventListener = new ValueEventListener() {
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String Bus_Driver = ds.child("Bus_Driver").getValue(String.class);
            Log.d(TAG, Bus_Driver);

    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage());

The output in your logcat will contain all bus driver names.

posted this

Have an answer?


Please login first before posting an answer.