简体   繁体   English

如何使用 android searchView 从 firebase firestore 中搜索数据列表

[英]How to search list of data from firebase firestore using android searchView

I'm using the Cloud Firestore of Firebase to store users and the android Searchview to provide search fonctionnality.我正在使用 Firebase 的 Cloud Firestore 来存储用户,并使用 android Searchview 来提供搜索功能。 When a user search for "jonathan" for example, if he begin typing "j" i want to bring in all users with the name starting par "j".例如,当用户搜索“jonathan”时,如果他开始输入“j”,我想引入名称以“j”开头的所有用户。 How can i achieve this?我怎样才能做到这一点?

Here is what i have tried:这是我尝试过的:

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);

        MenuItem search = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) search.getActionView();

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String query) {
                //Toast.makeText(MainActivity.this, "SEARCH " + query, Toast.LENGTH_LONG).show();
                searchUsers(query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                //Toast.makeText(MainActivity.this, "SEARCH " + newText, Toast.LENGTH_LONG).show();
                searchUsers(newText);
                return false;
            }
        });

        return true;
    }

Getting the user from Firebase:从 Firebase 获取用户:

private void searchUsers(String recherche) {
    if(recherche.length() > 0)
    recherche = recherche.substring(0,1).toUpperCase() + recherche.substring(1).toLowerCase();
    listUsers = new ArrayList<>();

    db.collection("users").whereGreaterThanOrEqualTo("name", recherche)
            .addSnapshotListener(new EventListener<QuerySnapshot>() {
                @Override
                public void onEvent(@Nullable QuerySnapshot snapshots,
                                    @Nullable FirebaseFirestoreException e) {
                    if (e != null) {
                        System.err.println("Listen failed:" + e);
                        return;
                    }
                    listUsers = new ArrayList<User>();

                    for (DocumentSnapshot doc : snapshots) {
                        User user = doc.toObject(User.class);
                        listUsers.add(user);
                    }
                    updateListUsers(listUsers);
                }
            });
}

This works only for the first letter "j" as soon as i add "ja" for example i still have all the "jonathan" displayed这仅适用于第一个字母“j”,只要我添加“ja”,例如我仍然显示所有“jonathan”

My way of searching is rather inefficient as I am using two recyclerviews, one is hidden and the other with the data visible.我的搜索方式效率很低,因为我使用了两个回收视图,一个是隐藏的,另一个是数据可见的。 All data in the document is fetched to an array and I query the array in real-time as you want.文档中的所有数据都被提取到一个数组中,我可以根据需要实时查询该数组。 The data remains synced always so it seems real-time.数据始终保持同步,因此看起来是实时的。 Not a good practice but it gets the job done for me.这不是一个好的做法,但它为我完成了工作。 If you need further help I can create a gist for you in that.如果您需要进一步的帮助,我可以为您创建一个要点。

The proper way would be to use this official link to search for exactly what you need Full-text search正确的方法是使用这个官方链接来准确搜索你需要的内容 全文搜索

Thanks to the suggestion of @Oby if found the solution.如果找到解决方案,感谢@Oby 的建议。 In fact i dont really need to query the database every time the search is triggered since i have the list of users.事实上,我真的不需要每次触发搜索时都查询数据库,因为我有用户列表。 I just have to make the search on the list like this: We get the list first:我只需要像这样在列表上进行搜索:我们先得到列表:

private void getUsers() {
        db.collection("users").whereEqualTo("etat", 1)
                .addSnapshotListener(new EventListener<QuerySnapshot>() {
                    @Override
                    public void onEvent(@Nullable QuerySnapshot snapshots,
                                        @Nullable FirebaseFirestoreException e) {
                        if (e != null) {
                            System.err.println("Listen failed:" + e);
                            return;
                        }
                        listUsers = new ArrayList<User>();

                        for (DocumentSnapshot doc : snapshots) {
                            User user = doc.toObject(User.class);
                            listUsers.add(user);
                        }
                        updateListUsers(listUsers);
                    }
                });
    }

Here is the search function:这是搜索功能:

private void searchUsers(String recherche) {
        if (recherche.length() > 0)
            recherche = recherche.substring(0, 1).toUpperCase() + recherche.substring(1).toLowerCase();

        ArrayList<User> results = new ArrayList<>();
        for(User user : listUsers){
            if(user.getName() != null && user.getName().contains(recherche)){
                results.add(user);
            }
        }
        updateListUsers(results);
    }

Here i notify the the Adapter of the RecyclerView that the data changed:在这里,我通知 RecyclerView 的适配器数据已更改:

private void updateListUsers(ArrayList<User> listUsers) {

        // Sort the list by date
        Collections.sort(listUsers, new Comparator<User>() {
            @Override
            public int compare(User o1, User o2) {
                int res = -1;
                if (o1.getDate() > (o2.getDate())) {
                    res = 1;
                }
                return res;
            }
        });

        userRecyclerAdapter = new UserRecyclerAdapter(listUsers, InvitationActivity.this, this);
        rvUsers.setNestedScrollingEnabled(false);
        rvUsers.setAdapter(userRecyclerAdapter);
        layoutManagerUser = new LinearLayoutManager(getApplicationContext());
        rvUsers.setLayoutManager(layoutManagerUser);
        userRecyclerAdapter.notifyDataSetChanged();
    }

And of course the SearchView:当然还有 SearchView:

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);

        MenuItem search = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) search.getActionView();

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override
            public boolean onQueryTextSubmit(String query) {
                //Toast.makeText(MainActivity.this, "SEARCH " + query, Toast.LENGTH_LONG).show();
                searchUsers(query);
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                //Toast.makeText(MainActivity.this, "SEARCH " + newText, Toast.LENGTH_LONG).show();
                searchUsers(newText);
                return false;
            }
        });

        return true;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何检索 firebase firestore Android 上的数据? - How to retrieve data on firebase firestore Android? 使用 flutter 从 firebase Firestore 获取数据 - fetching data from firebase firestore using flutter 如何使用 NextJs API、Firebase Firestore、axios 和 TypeScript 从 Firebase 集合中获取数据? - How do I get data from Firebase collection using NextJs API, Firebase Firestore, axios and TypeScript? 如何使用 firebase function 从云 Firestore 读取数据并循环并将其推送到列表 - How to read data from cloud firestore with firebase function and loop and push it to list 如何在已经从 Firestore KOTLIN 获取 arrayList 的片段上实现 SearchView - How to implement SearchView on fragment that is already fetching arrayList from firestore KOTLIN 如何从 Firebase Firestore 获取地理点作为列表<latlng>对于 Flutter 中的折线?</latlng> - How to get geopoints from Firebase Firestore as List<LatLng> for a Polyline in Flutter? 如何使用 excel 或 google 电子表格或 CSV 使用 excel 导入 firebase firestore 数据库中的批量数据 - How to import bulk data in firebase firestore database from excel or google spreadsheet or CSV using flutter 如何从 firebase firestore 获取数据并将数据存储在 useState 钩子中 - How to fetch data from firebase firestore and store the data in useState hook 如何将数据从 Firebase Firestore 模拟器导出到实际的 Firebase Firestore 数据库 - How to export data from Firebase Firestore emulator to actual Firebase Firestore database 如何使用 Android 在 RecyclerView 中显示来自 Firestore 的数据? - How to display data from Firestore in a RecyclerView with Android?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM