Use @Exclude to Prevent a Field from Storing to Firebase Firestore in Android with Kotlin data class

Опубликовано: 28 Сентябрь 2024
на канале: Brandan Jones
1,561
17

If you have a DTO or data class that you are storing to Firebase Cloud Firestore, it will store all public fields (attributes/getter setters) by default. What if you don't want a specific field to store to Firebase Cloud Firestore? You can place an @Exclude annotation above or before the public getter method, and Firebase will not persist that item. If you have a Kotlin data class, you may need to refactor the attribute, and remove it from the constructor, so that you can apply the @Exclude annotaiton.

In this video, I give an overview of why you want to do this, especially when master/detail records that have an object association in your program, and you want the detail to be its own Firestore collection, instead of part of the master record's JSON. Then I show how the application currently works, where it does persist the detail record in the master record's JSON object. Next, I refactor my Kotlin data class, and I remove the attribute declaration from the constructor. I create a private attribute of the data class, and then expose it through a public variable with a getter/setter method, as is a commonly accepted practice for encapsulation with Kotlin. I annotate the getter method with the @Exclude annotation. Finally, I run the program again, and show that the @Exclude annotated property does not store to Firebase Cloud Firestore. We can put this in its own Firestore collection, but that's not part of this video; we'll handle that in another video.

This video is part of a playlist, available at:    • Learning Module 2 3048 Q  

All source code is freely available on GitHub, at: https://github.com/discospiff/MyPlant...