【问题标题】:How to get all documents from collection according to specific field from Firestore [closed]如何根据Firestore中的特定字段从集合中获取所有文档[关闭]
【发布时间】:2020-02-25 12:42:49
【问题描述】:

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

这是数据库的图片:

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

      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}

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

【问题讨论】:

    标签: android firebase kotlin google-cloud-firestore


    【解决方案1】:

    小写大写最可能出现的问题。你的问题可能和这个question类似

    我可以看到你在数据库中描述的城市值是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()
        }
    

    【讨论】:

      【解决方案2】:

      这个我试过了,但是不行

      它不起作用,因为您在 for 循环的每次迭代中都创建了一个 chatAdapter 对象。为了解决这个问题,将最后四行代码移到循环之外。循环内部应该只存在:

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

      通过这种方式,您填充列表并仅在列表充满对象时设置适配器。

      【讨论】:

      • 实际上,问题是我没有在 arrayList 中获取数据。我想知道如何检索数据
      • 如果您尝试记录Log.d(TAG, document.toObject(chatModel::class.java).city),logcat 中会打印出什么?
      • 它只从 firestore 获取最后一个文档
      • 它应该打印每个名字。您是否尝试过将这些行排除在循环之外?
      • 是的,我已经尝试了所有这些代码,但它只能让我得到最后一个文档
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-28
      • 1970-01-01
      • 1970-01-01
      • 2021-05-30
      • 2019-12-29
      • 2023-03-08
      • 1970-01-01
      相关资源
      最近更新 更多