本文介绍了使用Kotlin的Firebase Firestore toObject()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在Kotlin项目中使用Firebase Firestore.一切都很好,除了我想用DocumentSnapshot.toObject(Class valueType)实例化对象时.

I try to use Firebase Firestore in a Kotlin project. Everything is going fine except when I want to instantiate an object with DocumentSnapshot.toObject(Class valueType).

这是代码:

FirebaseFirestore
    .getInstance()
    .collection("myObjects")
    .addSnapshotListener(this,
    { querySnapshot: QuerySnapshot?, e: FirebaseFirestoreException? ->

        for (document in querySnapshot.documents) {

            val myObject = document.toObject(MyObject::class.java)

            Log.e(TAG,document.data.get("foo")) // Print : "foo"
            Log.e(TAG, myObject.foo) // Print : ""
        }
    }
})

如您所见,当我使用documentChange.document.toObject(MyObject::class.java)时,实例化了我的对象,但未设置内部字段.我知道Firestore需要模型具有空的构造函数.这是模型:

As you can see, when I use documentChange.document.toObject(MyObject::class.java), my object is instantiated but the inner fields are not set.I know that Firestore needs the model to have an empty constructor. So here is the model :

class MyObject {

    var foo: String = ""

    constructor(){}

}

有人可以告诉我我在做什么错吗?

Can somebody tell me what I'm doing wrong?

谢谢

推荐答案

您忘了在公共构造函数中包含参数,或者也可以仅使用具有默认值的数据类,就足够了:

You forgot to include the public constructor with arguments, or you can also just use a data class with default values, it should be enough:

data class MyObject(var foo: String = "")

这篇关于使用Kotlin的Firebase Firestore toObject()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-15 05:33