Home > front end >  Kotlin - Firestore toObject method not working as intended
Kotlin - Firestore toObject method not working as intended

Time:11-18

I am using Firestore for my Android project and I am using the following code to convert the fetched document to a custom data class

val userData = user.toObject(UserData::class.java)!!

Now this line works perfectly when no code obfuscation is happening, however, with obfuscation, this line does not fail but rather does not copy the user document data to the userData. so I think the issue might be with Firestore and code obfuscation.

Does anyone else have had this issue before?

CodePudding user response:

toObject() method uses reflection to fill up your UserData model from the user document. Now that your UserData class is getting obfuscated, Firestore is not able to map the values in document to the model class.

To fix this, you need to disable code obfuscation for all the data models that you are using in Firebase.

The easiest fix is to add a @Keep annotation to your data class.

@Keep
data class UserData(...)

If you have a lot of such models, you can disable obuscation for an entire file or package by adding more rules to your proguard-rules.pro.

For example, this statement will keep all the classes intact inside model package while code shrinking and obfuscation:

-keep class com.example.app.data.models.** { *; }

Check out the documentation for more such rules.

  • Related