0
@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.

Abhinav Suman
  • 940
  • 1
  • 9
  • 29
MaaAn13
  • 264
  • 5
  • 24
  • 54
  • Possible duplicate of [How to make a RealmList parcelable](https://stackoverflow.com/questions/43619845/how-to-make-a-realmlist-parcelable) – Hemant Parmar Aug 14 '18 at 05:17
  • @HemantParmar In given example, there's no `@Parcelize` as well as an example for primitive list type of String. – MaaAn13 Aug 14 '18 at 05:18
  • If you need to pass object between activity using `Intent`,1.Just pass id and then getObj by id, 2. Get Object from realm then pass un-managed that object, 3. Convert that object to Json and pass as `String`. Check out this [answer](https://stackoverflow.com/a/43621950/1283715). – Khaled Lela Aug 14 '18 at 05:19
  • @KhaledLela I followed the "kotlin" example and I see some type of "Converter" classes that are made for custom object. In my case the type of list is String. Isn't there a way to avoid `Converter` classes like that as the type of my list is primitive and should/might be supported by Realm itself? – MaaAn13 Aug 14 '18 at 05:37

1 Answers1

3

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 { ... }
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428