How to make RealmList<String> Parcelable?

我们两清 提交于 2019-12-25 02:27:12

问题


@Parcelize open class TestClass(
        @SerialName("title")   
        var title: String,
        @SerialName("list")   
        var list: RealmList<String>    
) : RealmObject() { ... }

How can I parcelize "list" variable in this implementation?
It says, that it's not possible to parcel this type of value even if I add @RawValue.
What's the alternative here? An example with explanation would be flawless.


回答1:


Similarly to this approach, you can do

fun Parcel.readStringRealmList(): RealmList<String>? = when {
    readInt() > 0 -> RealmList<String>().also { list ->
        repeat(readInt()) {
            list.add(readString())
        }
    }
    else -> null
}

fun Parcel.writeStringRealmList(realmList: RealmList<String>?) {
    writeInt(when {
        realmList == null -> 0
        else -> 1
    })
    if (realmList != null) {
        writeInt(realmList.size)
        for (t in realmList) {
            writeString(t)
        }
    }
}

Then you can do

object StringRealmListParceler: Parceler<RealmList<String>?>  {
    override fun create(parcel: Parcel): RealmList<String>? = parcel.readStringRealmList()

    override fun RealmList<String>?.write(parcel: Parcel, flags: Int) {
        parcel.writeStringRealmList(this)
    }
}

Now you can do

@Parcelize 
open class TestClass(
        @SerialName("title")   
        var title: String = "",
        @SerialName("list")   
        var list: @WriteWith<StringRealmListParceler> RealmList<String>? = null
) : RealmObject(), Parcelable { ... }


来源:https://stackoverflow.com/questions/51834124/how-to-make-realmliststring-parcelable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!