android - 从 Firestore 获取对象数组
问题描述
我从 firestore 获取数据将其放入 ArrayList
arraylist=document.get("questionsList") as ArrayList<Question>
Toast.makeText(context, arraylist.size, Toast.LENGTH_LONG).show()
当我需要从 Arraylist 获取问题项时打印 Array put 的大小时它可以
Toast.makeText(context, arraylist!![0].question, Toast.LENGTH_LONG).show()
结果是 java.util.HashMap 不能转换为 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 了,但我相信它会是这样的:
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()
另外,要小心,!!
因为如果对象为空,它将导致运行时异常。
推荐阅读
- python - Blender Python 对象“分组”
- css - 在 Divi 主题中删除边距的问题
- python-2.7 - 具有绝对函数的隐式图的问题
- ruby-on-rails - 在没有模型的情况下使用 form_with 时的 Rails 和白名单参数,
- android - 为什么我最近从运行 Android 10 的三星设备上收到这么多 InflateException 崩溃?
- ios - RxSwift 上有某种优先级运算符吗?
- macos - 在 Catalina 上手动编译后的 Apache Xdebug 错误
- python - 生成所有可能的有序字符串排列
- java - CriteriaQuery 返回错误结果
- python - 我尝试在 Windows 10 上为 python 3.8.1 安装 kivy,但出现此错误