0

I have a class User that implements the Parcelable interface. User also has a property of type MutableList<String>. I would like to know how to read/write this type for Parcelable.

Here's my code so far

data class User(
    val contactNumber: String,
    val email: String,
    val fullName: String,
    var instanceToken: String,
    val isAdmin: Boolean,
    val isValid: Boolean,
    val organization: String,
    val registrationTokens: MutableList<String>,
    val uid: String,
    val unitNumber: String
) : Parcelable {

    constructor(source: Parcel) : this(
        source.readString() ?: "",
        source.readString() ?: "",
        source.readString() ?: "",
        source.readString() ?: "",
        source.readBoolean(),
        source.readBoolean(),
            source.readString() ?: "",
            source.readStringList(),
            source.readString() ?: "",
        source.readString() ?: ""
    )

    override fun writeToParcel(dest: Parcel?, flags: Int) {
        dest?.let {
            it.writeString(contactNumber)
            it.writeString(email)
            it.writeString(fullName)
            it.writeString(instanceToken)
            it.writeBoolean(isAdmin)
            it.writeBoolean(isValid)
            it.writeString(organization)
            it.writeStringList(registrationTokens)
            it.writeString(uid)
            it.writeString(unitNumber)
        }

    }

For the write part, there's a writeStringList() method which is convenient. But for the read part, the provided readStringList() does not actually return MutableList<String>. It only returns Unit / void. Hence, it spits out a compilation error.

What is the proper way of doing this?

Quick learner
  • 10,632
  • 4
  • 45
  • 55
fishhau
  • 459
  • 1
  • 3
  • 15

1 Answers1

0

Use createStringArrayList(). readStringList is intended to reuse a single List instead of creating a new one each time, this isn't what you want here.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
  • Thanks for the helpful info. I'll have to cast it like so: `source.createStringArrayList() as MutableList`. Is that correct? Also, is my usage of `writeStringList()` above correct? – fishhau May 29 '19 at 07:17
  • There should be no need to cast anything; it returns an `ArrayList` which is a subtype of `MutableList`. `writeStringList` should be correct, yes. (And look into `@Parcelize` as the comments mentioned.) – Alexey Romanov May 29 '19 at 12:22
  • Thanks for the clarification. I was doubtful of using Parcelize when I started the project since some developers reported unexpected behavior with it sometimes as it's still an experimental feature. I didn't want to take the risk facing difficulties down the road so I manually implemented `Parcelable`. Once it is not experimental anymore, I'll for sure implement it in my project. It's nice not having to worry about modifying the `Parcel` methods everytime I need to add or remove a property. – fishhau May 30 '19 at 00:44