I am using Room and Kotlin data class. Such as,
@Entity(tableName = "Person")
@Parcelize
class Test(@ColumnInfo(name = "name") var name:String) : Parcelable{
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "ID")
var id: Long? = null
}
I can create the instance using the constructor and insert the data. I am also getting a warning "property would not be serialized into a 'parcel'"
. When I was trying to send the object through a bundle, the id is missing, which is expected as the warning says so. How can I add that member ID
in the parcel? I am not keeping the ID in the constructor as I want them to be generated automatically.
Usage. Just add the @Parcelize annotation to a class implementing the Parcelable interface and the Parcelable implementation will be generated automatically. This is the same example as in the previous article, in just 2 lines of code. The class can be a data class but it's optional.
The Android's Parcelable is an interface on which, the values can be written and read from a Parcel. The implementation of the Parcelable interface allows an object to be passed between the different Android components like, activity and fragment.
You can find this information with the documentation:
@Parcelize
requires all serialized properties to be declared in the primary constructor. Android Extensions will issue a warning on each property with a backing field declared in the class body. Also,@Parcelize
can't be applied if some of the primary constructor parameters are not properties.If your class requires more advanced serialization logic, you can write it inside a companion class:
@Parcelize
data class User(val firstName: String, val lastName: String, val age: Int) : Parcelable {
private companion object : Parceler<User> {
override fun User.write(parcel: Parcel, flags: Int) {
// Custom write implementation
}
override fun create(parcel: Parcel): User {
// Custom read implementation
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With