如何在Firebase数据库中的字符串中任何地方搜索-Android [英] How to search anywhere in string in Firebase Database - Android

查看:37
本文介绍了如何在Firebase数据库中的字符串中任何地方搜索-Android的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在我的android应用中实现了firebase实时数据库,一切都很好.我正在尝试添加搜索功能,并且仅通过起始单词匹配就可以搜索数据库.下面是我的数据库快照:

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:

我正在查询movieName.现在,我可以搜索查询字符串是否为Pets/Pe/pet.但是,当我搜索动物时,结果为零.因此,基本上我正在寻找的是在字符串中任何位置使用查询文本搜索数据库.即,我应该能够搜索Animals/and/pets并获得包含搜索查询的结果.

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

推荐答案

要在字符串中查找字符串,请使用以下代码:

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

如您所见,我们在数据库中查询所有电影名称,然后在 movieName 中搜索所需的单词.

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

这篇关于如何在Firebase数据库中的字符串中任何地方搜索-Android的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆