簡體   English   中英

如何在 Kotlin 中獲取 Firebase 中的數組類型數據?

[英]How to get Array type data in Firebase in Kotlin?

我在 firebase 中有這種類型的數組,但是如何獲取它並在 kotlin 中使用我能夠以字符串形式獲取,但如何將其作為data class
像這樣

data class Comment(
    val uid: String,
    val comment: String,
    val stamp: Timestamp
)

這是獲取字符串的代碼

var text by remember { mutableStateOf("loading...") }
FirebaseFirestore.getInstance().collection("MyApp")
  .document("Something").get().addOnSuccessListener {
     text = it.get("Comments").toString()
}

檢查這個圖像

Firebase 有一個toObject方法,可用於將您的文檔轉換為自定義 object。

db.collection("Comments")
    .get()
    .addOnSuccessListener { documents ->
        for (document in documents) {
            val comment = document.toObject<Comment>()
        }
    }

Comment數據 class 也應該定義默認值。 所以,應該是這樣的...

data class Comment(
    val uid: String = "",
    val comment: String = "",
    @ServerTimeStamp val stamp: Date? = null
)

我得到 ArrayLists with HashMaps 代表你的評論實體只是使用這個:

        firestore.collection(YOUR_COLLECTION)
        .get()
        .await()
        .documents.map { document ->
            try {
                val comments = document.get("Comments")
            } catch (e: Exception) {
                e.printStackTrace()
            }
        

的確,我們需要進一步解開這個糾結

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM