Rajitha Perera
Rajitha Perera

Reputation: 1621

How to search for a values of Child in firebase Android

enter image description here

DatabaseReference databaseReference=mDatabase;
        String queryText="Hotel";
        databaseReference.orderByChild("Coupon")
                .startAt(queryText)
                .endAt(queryText+"\uf8ff");

Here I attached the code which I used to get child names of "Coupon" when I entered the "Hotel" query under the Coupon.But I got blank.I supposed to get Hotel1,Hotel2 object.I'm new to firebase.So hope your support .Thanks in advance.

Upvotes: 2

Views: 4844

Answers (2)

Greg Alpha
Greg Alpha

Reputation: 31

Don't load your whole database to filter out needed data. It produces unnecessary traffic which has to be loaded, calculated and deleted. Instead, use:

DatabaseReference myRef = FirebaseDatabase.getDatabaseReference();

Query searchQuery = myRef.child("Coupon").orderByChild("hotel").equalTo("yourSearchString");

To make this code work, you also have to add indexOn on your corresponding attribute in the rules (of Firebase Database console).

Upvotes: 2

Kurt Acosta
Kurt Acosta

Reputation: 2537

In the Web version, they use something called ElasticSearch, you could try to read more here: https://firebase.googleblog.com/2014/01/queries-part-2-advanced-searches-with.html

But for Android, I think there isn't any functionality to perform a search like that. What I would do is to query all the records then filter them myself:

DatabaseReference databaseReference = mDatabase;
mDatabase.addValueEventListener(new ValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
    for(DataSnapshot val : dataSnapshot.getChildren()){
        //I am not sure what record are you specifically looking for
        //This is if you are getting the Key which is the record ID for your Coupon Object
        if(val.getKey().contains("Hotel")){
            //Do what you want with the record
        }

        //This is if your are querying for the hotel child
        if(val.child("hotel").getValue(String.class).contains("Hotel")){
            //Do what you want with the record
        }
    }
}
@Override
public void onCancelled(FirebaseError firebaseError) {

}

}

Upvotes: 2

Related Questions