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

3830 views java
2

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.

answered question

1 Answer

11

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.

posted this

Have an answer?

JD

Please login first before posting an answer.