首页 > 解决方案 > 如何根据 Firestore 中的特定字段从集合中获取所有文档

问题描述

我在“Firestore”中有这些数据,我想根据“城市”获取所有文档,就像所有拥有城市“卡拉奇”并存储在arrayList“chatModel”类型的用户一样,我想在 recyclerView 中显示这些数据

这是数据库的图像:
这是数据库的图像

我已经尝试过了,但它只是让我从集合中获得最后一个文档。

      firestore.collection("USERS")
        .whereEqualTo("city",cityName)
        .get()
        .addOnSuccessListener { documents ->
            for (document in documents) {

                arrayList.add(document.toObject(chatModel::class.java))

                Log.i("Info", "${document.id} => ${document.data}")


            }

            val adapter = chatAdapter(context!!, arrayList)
            chatRecyclerView.layoutManager = LinearLayoutManager(context,
                LinearLayoutManager.VERTICAL,false)
            chatRecyclerView.adapter = adapter
            adapter.notifyDataSetChanged()
        }

这是 Logcat 结果:

v21GH5sBi3SdIb3v3xsp3ob64S23 => {username=Muhammad Rizwan, Email=mr1017753@gmail.com, city=Karachi, ProfileImageUrl=https://firebasestorage.googleapis.com/v0/b/me2wee-1b547.appspot.com/o/USERS-MEDIA%2Fv21GH5sBi3SdIb3v3xsp3ob64S23?alt=media&token=193c4013-c580-45dc-b63d-fee1ef13caba}

这是包含城市“卡拉奇”的所有文件的屏幕截图,但它只得到最后一个

在此处输入图像描述

标签: androidfirebasekotlingoogle-cloud-firestore

解决方案


小写大写最可能的问题。你的问题可能类似于这个问题

正如我所见,您在数据库中描述的城市值是karachi小写,但输出您提供了大写的结果。

firestore.collection("USERS").get()
    .addOnSuccessListener { documents ->
        for (document in documents) {
            if(document.get("city").equals("karachi") || document.get("city").equals("Karachi")){
                arrayList.add(document.toObject(chatModel::class.java));
            }
        }

        val adapter = chatAdapter(context!!, arrayList)
        chatRecyclerView.layoutManager = LinearLayoutManager(context,
            LinearLayoutManager.VERTICAL,false)
        chatRecyclerView.adapter = adapter
        adapter.notifyDataSetChanged()
    }

推荐阅读