Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to search anywhere in string in Firebase Database - Android

I have implemented firebase realtime database in my android app, everything is fine. I am trying to add a a search function and I am able to search the database with only starting word match. Below is my database snapshot:

enter image description here

I am querying for movieName. Right now I am able to search if the query string is Pets/Pe/pet. But when I search for Animals, I get zero results. So, basically what I am looking for is searching the database with query text anywhere in the string. ie., I should be able to search Animals/and/pets and should get the results which contain the search query.

Below is my code so far.

mDatabaseReference.child("recent").getRef().orderByChild("movieName").startAt(query)
                    .endAt(query + "\uf8ff")
like image 457
Darshan Gowda Avatar asked Sep 17 '17 07:09

Darshan Gowda


1 Answers

To seach for a string within a String please use the following code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference animalsRef = rootRef.child("Animals");
ValueEventListener eventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        Boolean found;
        String search = "Animals";
        for(DataSnapshot ds : dataSnapshot.getChildren()) {
            String movieName = ds.child("movieName").getValue(String.class);
            found = movieName.contains(search);
            Log.d("TAG", movieName + " / " + found);
        }
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {}
};
animalsRef.addListenerForSingleValueEvent(eventListener);

As you see, we query the database for all the movie names and then search for the desired word within the movieName.

like image 59
Alex Mamo Avatar answered Oct 15 '22 22:10

Alex Mamo