0

Screen shot of my Database

enter image description here

I would like to query my database by returning the names of all parents nodes which have certain similar child nodes.

I am already fetching the name of one parent with respect to it's child, but I want to fetch the name of all parents with similar child value.

Suppose, I want to get the names of the Hotels which have the similar child node value of 2000 and have a Rating of 3-star.

final List<String> hotelNames = new ArrayList<String>();
final Query userQuery = FirebaseDatabase.getInstance().getReference().child("F-5").orderByChild("HotelTypeTwo");

userQuery.equalTo(varX).addListenerForSingleValueEvent(
        new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot foodSnapshot: dataSnapshot.getChildren()) {


                    hotelNames.add(foodSnapshot.getKey());


                    for (int i=0;i < hotelNames.size();i++)
                    {
                        Log.i("Value of element "+i,hotelNames.get(i));

                    }

                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        }
);
KENdi
  • 7,576
  • 2
  • 16
  • 31

1 Answers1

2

So to get all hotels where HotelTypeTwo is equal to Desi and get according to your screenshot as results: Islamabad Hotel and Islamabad Mariott Hotel, please use the follwing lines of code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference fRef = rootRef.child("F-5");
Query query = fRef.orderByChild("HotelTypeTwo").equalTo("Desi");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String hotelName = ds.getKey();
            Log.d(TAG, hotelName);
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
    }
};
query.addListenerForSingleValueEvent(valueEventListener);

The result in your logcat will be:

Islamabad Hotel
Islamabad Mariott Hotel

Unfortunately, querying on multiple properties is not permitted in Firebase. A workaround can be my answer from the following post:

However, in Firestore compound queries are permitted:

citiesRef.whereEqualTo("state", "CO").whereEqualTo("name", "Denver");

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193