Muzzammil Hussain
Muzzammil Hussain

Reputation: 298

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

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()) {
                if(busInfo.getBus_Driver().equalsIgnoreCase(driverName))
                {
                    saveData()

                    break;
                    //}
                }
            }

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

Upvotes: 2

Views: 92

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138844

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() {
    @Override
    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);
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage());
    }
};
query.addListenerForSingleValueEvent(valueEventListener);

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

Upvotes: 2

Related Questions