Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Firestore toObject() with Kotlin

Tags:

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

like image 212
Valentin Avatar asked Oct 08 '17 16:10

Valentin


1 Answers

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 = "") 
like image 59
Guilherme V. Avatar answered Oct 11 '22 13:10

Guilherme V.