Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parcelise member variable other than constructor in data class while using @Parcelize

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.

like image 561
sadat Avatar asked Nov 15 '18 04:11

sadat


People also ask

How do I use Parcelize annotations?

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.

What is @parcelize?

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.


1 Answers

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
        }
    }
}
like image 165
tynn Avatar answered Oct 17 '22 18:10

tynn