【问题标题】:How to get array data from Firestore? Android Kotlin如何从 Firestore 获取数组数据?安卓科特林
【发布时间】:2023-02-14 17:52:19
【问题描述】:

我在 Firestore 中有一个数组。我怎样才能得到数组项?我需要streamers数组类型的字符串。

我尝试的是:

firebaseFireStore.collection("Agencies")
        .addSnapshotListener { snapshot, e ->
            if (e == null) {
                val documents = snapshot?.documents
                if(documents != null) {
                    val list = mutableListOf<Ajanslar>()
                    for (document in documents) {

                        val agencyName = document.get("agencyName").toString()
                        val coverImage = document.get("coverImage").toString()
                        val owner = document.get("owner").toString()
                        val platform = document.get("platform").toString()
                        val streamers = document.get("streamers")
                        val newAjans = Ajanslar(agencyName,coverImage,owner,platform,streamers)
                        list.add(newAjans)
                    }
                    ajansListRepo.value = list
                }
            }
        }

彩带报错并说Type mismatch. Required: kotlin.collections.ArrayList&lt;String&gt; /* = java.util.ArrayList&lt;String&gt; */ Found: Any?

我的 Firestore 是这样的:

我在 Java 中找到了这样的答案,但我做不到。

rootRef.collection("products").document("06cRbnkO1yqyzOyKP570").get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
    if (task.isSuccessful()) {
        DocumentSnapshot document = task.getResult();
        if (document.exists()) {
            ArrayList<String> list = (ArrayList<String>) document.get("ip_range");
            Log.d(TAG, list.toString());
        }
    }
}

});

【问题讨论】:

    标签: android firebase kotlin google-cloud-platform google-cloud-firestore


    【解决方案1】:

    我写了 answer 并且在 Kotlin 中解决方案非常简单。正如我在您的屏幕截图中看到的,streamers 字段是一个字符串数组。当您调用 DocumentSnapshot#get() 时,返回的对象类型是 Any 而不是 List&lt;String&gt;。如果需要,您必须显式地对此类对象执行强制转换。所以请更改以下代码行:

    val streamers = document.get("streamers")
    

    进入:

    val streamers = document.get("streamers") as List<String>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-30
      • 1970-01-01
      • 2021-07-23
      • 1970-01-01
      相关资源
      最近更新 更多