Search code examples
javaandroidserializationparcelable

Using both Parcelable class and Serializable in one class


I have class Data with some properties, where one of the property is a class which implements Serializable and another one implements Parcelable, other properties is String.

And I want to make this Class (Data) implement Serializable.

Is there any problems during serialization of Data class with property which implements Parcelable, but not implements Serializable?


Solution

  • There are no issues as you don't introduce any new properties for the Parcelable implementation. Standard implementation merely provides you some helper methods describeContents and writeToParcel and a static CREATOR object, which will not be part of the Serialized content.

    example:

     class MyParcelable private constructor(`in`: Parcel) : Parcelable {
         private val mData: Int = `in`.readInt()
    
         override fun describeContents(): Int {
             return 0
         }
    
         override fun writeToParcel(out: Parcel, flags: Int) {
             out.writeInt(mData)
         }
    
         companion object {
             val CREATOR: Parcelable.Creator<MyParcelable?>
                     = object : Parcelable.Creator<MyParcelable?> {
                 override fun createFromParcel(`in`: Parcel): MyParcelable? {
                     return MyParcelable(`in`)
                 }
    
                 override fun newArray(size: Int): Array<MyParcelable?> {
                     return arrayOfNulls(size)
                 }
             }
         }
     }