Firebase Firestore toObject() with Kotlin

血红的双手。 提交于 2020-01-12 12:48:31

问题


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

Here is the code :

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

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?

Thank you


回答1:


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 = "")



回答2:


In my case I was getting a NullPointerException because there wasn't a default constructor. Using a data class with default values fixed the error.

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



回答3:


class MyObject {

    lateinit var foo: String

    constructor(foo:String) {
        this.foo = foo
    }

    constructor()

}


来源:https://stackoverflow.com/questions/46633412/firebase-firestore-toobject-with-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!