Firebase Firestore toObject () with Kotlin

I am trying to use Firebase Firestore in a Kotlin project. Everything goes well, except when I want to instantiate an object using 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 created, but the internal fields are not set. I know that Firestore needs a model in order to have an empty constructor. So here is the model:

class MyObject {

    var foo: String = ""

    constructor(){}

}

Can someone tell me what I'm doing wrong?

thanks

+14
source share
3 answers

, , :

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

NullPointerException, . ​​.

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

    lateinit var foo: String

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

    constructor()

}
0
source

All Articles