从 Firestore 获取对象数组 [英] Get Array of object From Firestore

查看:21
本文介绍了从 Firestore 获取对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从 firestore 获取数据并将其放入 ArrayList

arraylist=document.get("questionsList") as ArrayList<Question>
Toast.makeText(context, arraylist.size, Toast.LENGTH_LONG).show()

当我打印数组的大小时就可以了当我需要从 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

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

推荐答案

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

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

Also, be careful with !! as it will cause a runtime exception if the object is null.

这篇关于从 Firestore 获取对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆