首页 > 解决方案 > 从 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

此处的 Firestore 图像中的文档

问题类

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)
        }
    }
}

标签: androidfirebasedictionaryarraylistkotlin

解决方案


您可以使用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()

另外,要小心,!!因为如果对象为空,它将导致运行时异常。


推荐阅读