Skip to content

Deserialization for list parcelable crashes when you call writeTypedList(null) first #30

@danielgomezrico

Description

@danielgomezrico

Current generated code for list of parcelables will crash if you put an empty list.

Error example

Caused by: java.lang.IllegalStateException: source.createTypedArrayL…(AvatarUrlHolder.CREATOR) must not be null

Example code

class AvatarUrlHolder(val id: Long, val url: String) : Parcelable {

  constructor(source: Parcel) : this(source.readLong(), source.readString())

  override fun describeContents() = 0

  override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
    writeLong(id)
    writeString(url)
  }

  companion object {
    @JvmField
    val CREATOR: Parcelable.Creator<AvatarUrlHolder> = object : Parcelable.Creator<AvatarUrlHolder> {
      override fun createFromParcel(source: Parcel): AvatarUrlHolder = AvatarUrlHolder(source)
      override fun newArray(size: Int): Array<AvatarUrlHolder?> = arrayOfNulls(size)
    }
  }

}

// Class that have the list
class People(val avatars: List<AvatarUrlHolder>) : Parcelable {

  constructor(source: Parcel) : this(
    source.createTypedArrayList(AvatarUrlHolder.CREATOR)
  )

  override fun describeContents() = 0

  override fun writeToParcel(dest: Parcel, flags: Int) = with(dest) {
    writeTypedList(agreedExpertsAvatars)
  }

  companion object {
    @JvmField
    val CREATOR: Parcelable.Creator<People> = object : Parcelable.Creator<People> {
      override fun createFromParcel(source: Parcel): People = People(source)
      override fun newArray(size: Int): Array<People?> = arrayOfNulls(size)
    }
  }
}

If you create the people with People(listOf()) the method writeTypedList will crash with:

Caused by: java.lang.IllegalStateException: source.createTypedArrayL…(AvatarUrlHolder.CREATOR) must not be null

Solution

This can be fixed if the generated code in the constructor looks like:

listOf<AvatarUrlHolder>().apply {
  source.readTypedList(this, AvatarUrlHolder.CREATOR)
}

instead of:

source.createTypedArrayList(AvatarUrlHolder.CREATOR)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions