Search code examples
androidkotlinparcelable

Parcelable with custom parcelable object


I have a class that has a member variable of type ArrayList<>. Both classes implement parcelable. I'm stuck on how to complete the class that has a reference to the other class.

Here is what I have:

data class Tab (val name: String, val title: String, val color: String, val sections: ArrayList<Section>) : Parcelable {

    constructor(parcel: Parcel) : this(
            parcel.readString(),
            parcel.readString(),
            parcel.readString(),
            parcel.readTypedList<Section>(sections, Section.CREATOR))

    override fun writeToParcel(dest: Parcel?, flags: Int) {
        dest?.writeString(name)
        dest?.writeString(title)
        dest?.writeString(color)
        dest?.writeTypedList<Section>(sections)
    }

    override fun describeContents(): Int {
        return 0
    }

    companion object CREATOR : Parcelable.Creator<Tab> {
        override fun createFromParcel(parcel: Parcel): Tab {
            return Tab(parcel)
        }

        override fun newArray(size: Int): Array<Tab?> {
            return arrayOfNulls(size)
        }
    }
}

Notice how this class has a value called sections that is an ArrayList<Section>. I need to write that variable to a parcelable, but it's not working.

For reference, here is the Section class. I think this one is OK:

data class Section(val type: String, val text: String, val imageName: String) : Parcelable {

    constructor(parcel: Parcel) : this(
            parcel.readString(),
            parcel.readString(),
            parcel.readString())

    override fun writeToParcel(dest: Parcel?, flags: Int) {
        dest?.writeString(type)
        dest?.writeString(text)
        dest?.writeString(imageName)
    }

    override fun describeContents(): Int {
        return 0
    }

    companion object CREATOR : Parcelable.Creator<Section> {
        override fun createFromParcel(parcel: Parcel): Section {
            return Section(parcel)
        }

        override fun newArray(size: Int): Array<Section?> {
            return arrayOfNulls(size)
        }
    }
}

It's the readTypedList and writeTypedList lines that are failing.

Thanks for any help.


Solution

  • First solution

    @Suppress("UNCHECKED_CAST")
    constructor(parcel: Parcel): this(parcel.readString(), parcel.readString(), parcel.readString(), parcel.readArrayList(Tab::class.java.classLoader) as ArrayList<Section>)
    

    Second solution

    constructor(parcel: Parcel): this(parcel.readString(), parcel.readString(), parcel.readString(), ArrayList<Section>()){
        parcel.readTypedList(sections, Section.CREATOR)
    }