Java – Android: firebase search query does not work properly

I'm new to Android application development I created a simple search query to search my firebase database by name (see the following code):

private void firebaseEventSearch(String name) {
    //query to search database based on text in text@R_969_2419@ - made case insensitive
    Query eventSearchQuery = eventRef.orderByChild("name").startAt(name.toUpperCase()).endAt(name.toLowerCase() + "\uf8ff");
    eventSearchQuery.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for (DataSnapshot eventSnapshot : dataSnapshot.getChildren()) {
                Event event = eventSnapshot.getValue(Event.class);
                events.add(event);
            }
            adapter.notifyDataSetChanged();
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });
}

It works normally in most cases, but when I enter the letter "a" or "B", it will display all database results - the search does not apply to both letters In addition, if I type a search string whose first letter matches the database entry, it will display the database entry, even if the rest of the string does not match it

I really appreciate it if someone can help me understand why this search query doesn't work properly

Solution

Firebase database queries are case sensitive Therefore, when you call orderbychild ("name"), all nodes are sorted by their name attribute If you look at an ASCII chart, you will find that this will result in the order of lowercase and uppercase characters:

A B C .... X Y Z a b c ... x y z

Your query will now get part of this data If you are searching for a, the slice is:

A B C .... X Y Z a

So it's more than you want

If you want to allow case insensitive searches on firebase, the most common (but not complete failure) way to implement it is to add an additional attribute to store the name in an irrelevant way For example “name_uppercase”:“ZUHRAIN”. With this, you can search:

eventRef.orderByChild("name_uppercase").startAt(name.toUpperCase()).endAt(name.toUpperCase() + "\uf8ff");

See also:

>Making a firebase query search not case sensitive > firebase query methods startat() taking case sensitive parameters > cloud firestore case insensitive sorting using query (for cloud firestore, it shows a safer way to do this)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>