我尝试在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 : ""
}
}
})
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,当我使用时documentChange.document.toObject(MyObject::class.java),我的对象被实例化,但内部字段未设置.我知道Firestore需要模型有一个空的构造函数.所以这是模型:
class MyObject {
var foo: String = ""
constructor(){}
}
Run Code Online (Sandbox Code Playgroud)
谁能告诉我我做错了什么?
谢谢