Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase Firestore Android can't deserialize object

I want to deserialize data from firebase firestore to a model (Foo)

data class Foo(
        var timestamp: Int = 0,
        var title: String = "",
        var question: String = "",
        var category: String = "",
        var content: String = "",
        var link: String = ""
) {
    fun Foo() {}
}

with query like this:

FirebaseFirestore.getInstance().collection(COLLECTION_NAME)
                .orderBy(ORDER_KEY, Query.Direction.DESCENDING)
                .limit(LIMIT)
                .get()
        .addOnSuccessListener { snapshot ->
            snapshot.documents.forEach {
                println(it.data) // data print successfully
                // got error java.lang.RuntimeException: Could not deserialize object. Failed to convert a value of type com.google.firebase.firestore.Blob to int (found in field 'timestamp')
                val foo = it.toObject(Foo::class.java)
            }
        }

but got error java.lang.RuntimeException: Could not deserialize object. Failed to convert a value of type com.google.firebase.firestore.Blob to int (found in field 'timestamp')

I use firebase version 11.6.2 in my android project

where data in firestore is like in this screenshot:

enter image description here

Any idea why deserialization failed?

like image 943
hakim Avatar asked Mar 17 '26 21:03

hakim


1 Answers

I think you are using the wrong datatype in your model class.

If your dataType is timestamp in firestore collection then use Date datatype to timestamp in your model currently you are using int.

in Java use this.

 public Date createdAt;
 public String createdBy;

For kotlin use this.

 val timestamp: Date? = null,
 var title: String = "",
 var question: String = "",
 var category: String = "",
 var content: String = "",
 var link: String = ""
like image 184
Nivrutti Pawar Avatar answered Mar 19 '26 11:03

Nivrutti Pawar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!