问题
I getting data from firestore put it in to ArrayList
arraylist=document.get("questionsList") as ArrayList<Question>
Toast.makeText(context, arraylist.size, Toast.LENGTH_LONG).show()
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()
the result is java.util.HashMap cannot be cast to Question
document in firestore image here
Question class
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)
}
}
}
回答1:
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()
Also, be careful with !!
as it will cause a runtime exception if the object is null.
来源:https://stackoverflow.com/questions/54647028/get-array-of-object-from-firestore