且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从Firestore获取对象数组

更新时间:2023-11-30 22:37:22

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