如何读取MutableList <string>到Parcelable?

时间:2019-05-29 07:04:59

标签: android kotlin parcelable

我有一个实现User接口的类ParcelableUser也具有类型MutableList<String>的属性。我想知道如何为Parcelable读/写这种类型。

到目前为止,这是我的代码

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)
        }

    }

对于写部分,有一个writeStringList()方法很方便。但是对于读取的部分,提供的readStringList()实际上并不返回MutableList<String>。它仅返回Unit / void。因此,它会吐出编译错误。

这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

使用createStringArrayList()readStringList旨在重用单个List,而不是每次都创建一个新的c = int(input("Hi",name,", would you like to get someone around you to choose your word to guess(1) or choose randomly from a preselected list(2)? "))