Reputation: 197
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()
}
Upvotes: 1
Views: 1337
Reputation: 348
I got ArrayLists with HashMaps represents my entities entities just using this:
val cleanAnswers: List<Answer> = (document.get(FIELD_ANSWERS)
as ArrayList<HashMap<String, Any>>).map {
Answer(
it[FIELD_VARIANT] as String,
it[FIELD_IS_CORRECT] as Boolean
)
}
My entity:
class Answer(val answer: String,
val isCorrect: Boolean) : Serializable
Upvotes: 0
Reputation: 1945
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
)
Upvotes: 1