从Firestore获取对象数组 [英] Get Array of object From Firestore
问题描述
我从firestore获取数据并将其放入ArrayList
arraylist=document.get("questionsList") as ArrayList<Question>
Toast.makeText(context, arraylist.size, Toast.LENGTH_LONG).show()
,当我打印Array的大小时还可以 当我需要从Arraylist获取问题项时放上
and its ok when I print the size of Array put when I need to get Question Item from Arraylist
Toast.makeText(context, arraylist!![0].question, Toast.LENGTH_LONG).show()
结果是 java.util.HashMap无法强制转换为Question
the result is java.util.HashMap cannot be cast to Question
问题课
class Question (var question:String,var choices:ArrayList<String>,var correctAnswer:String
,private var userAnswer:String): Parcelable {
constructor(parcel: Parcel) : this(
parcel.readString()!!, arrayListOf<String>().apply {
parcel.readString()
},
parcel.readString()!!,
parcel.readString()!!
)
constructor():this(question="",choices = ArrayList<String>(),correctAnswer = "",userAnswer = "")
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeString(question)
parcel.writeString(correctAnswer)
parcel.writeString(userAnswer)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Question> {
override fun createFromParcel(parcel: Parcel): Question {
return Question(parcel)
}
override fun newArray(size: Int): Array<Question?> {
return arrayOfNulls(size)
}
}
}
推荐答案
您可以使用document.toObject
将Firestore结果转换为Kotlin类.如果仅在字段上使用get
,则将获得一个HashMap.在您的情况下,您可以创建一个具有questionsList
属性的类,然后将其强制转换为您的类.我已经有几个月没有用过Kotlin了,但是我相信它会是这样的:
You can use document.toObject
to cast your Firestore result to a Kotlin class. If you just use get
on the field you will get a HashMap. In your case you could create a class that has a questionsList
property and then cast it to your class. I haven't used Kotlin in a few months, but I believe it would be something like this:
data class MyQuestionList(
var questionsList: ArrayList<Question>
)
val myQuestionList = document.toObject(MyQuestionList::class.java)
Toast.makeText(context, myQuestionList.questionsList!![0].question, Toast.LENGTH_LONG).show()
另外,请谨慎使用!!
,因为如果该对象为null,它将导致运行时异常.
Also, be careful with !!
as it will cause a runtime exception if the object is null.
这篇关于从Firestore获取对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!