How to get Array type data in Firebase in Kotlin?

Issue

I have this type of array in firebase but how to fetch it and use in kotlin
I was able to get as String but how to get its as a data class
Like this

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

and here’s the code of getting string

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

Check this iage

Solution

Firebase has a toObject method that can be used to turn your document into a custom object.

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

The Comment data class should also define default values. So, it should be like…

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

Answered By – danartillaga

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published