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

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.






then just check simple refrence.equalto(name) and trigger action.?

– Atif AbbAsi
Sep 16 '18 at 11:49




1 Answer
1



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.



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you agree to our terms of service, privacy policy and cookie policy