简体   繁体   中英

How to fetch all parent nodes with similar child nodes on Firebase database Android?

Screen shot of my Database

在此处输入图片说明

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) {

            }
        }
);

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM