使用Kotlin的Firebase Firestore toObject()

时间:2017-10-08 16:31:37

标签: kotlin google-cloud-firestore

我尝试在Kotlin项目中使用Firebase Firestore。一切都很顺利,除非我想用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需要模型有一个空的构造函数。所以这是模型:

class MyObject {

    var foo: String = ""

    constructor(){}

}

有人可以告诉我我做错了吗?

谢谢

3 个答案:

答案 0 :(得分:15)

您忘记使用参数包含公共构造函数,或者您也可以使用具有默认值的数据类,这应该足够了:

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

答案 1 :(得分:5)

在我的情况下,我得到了一个 NullPointerException ,因为没有默认的构造函数。 使用具有默认值的数据类可以修复错误。

data class Message(
        val messageId : String = "",
        val userId : String = "",
        val userName : String = "",
        val text : String = "",
        val imageUrl : String? = null,
        val date : String = ""
)

答案 2 :(得分:0)

{
"_id" : ObjectId("5cc7d8e88c33e065c56b0883"),
"sons" : [ 
    {
        "id" : "son1",
        "age" : 40.0
    }, 
    {
        "id" : "son2",
        "age" : 40.0
    }
]
}
相关问题