0

I've a list of strings that I want to parcelize and then put into Realm.

public class X extends RealmObject ... 

private @SerialName("ha") RealmList<String> list;

public void writeToParcel(Parcel out, int i) {
    //how to do this?  
}

private X(Parcel in) {
    ///how to do this?  
}

I'm not sure how can I writeToParcel and readToParcel RealmList?

MaaAn13
  • 264
  • 5
  • 24
  • 54
  • have you tried setting write and read as a String array in parcel methods? – Sharjeel Sep 03 '18 at 14:17
  • Well, it's different type. Writing array requires String values not whole RealmList. This means I have to create some kind of method that does that for me, which looks like alot more like creating parcelize mechanism and storing RealmList values, where T is object. I thought that there should be alot easier method of doing this, as they now support RealmList as a primitive list. This should be a common situation. Maybe someone can share their solutions to this? – MaaAn13 Sep 03 '18 at 14:24
  • I was going to say https://stackoverflow.com/a/51840457/2413303 but that's Kotlin. – EpicPandaForce Sep 03 '18 at 15:30

1 Answers1

1

You can turn any collection into Parcelable by writing out its size and then re-constructing it.

private @SerialName("ha") RealmList<String> list;

public void writeToParcel(Parcel out, int i) {
    out.writeInt(list != null ? 1 : 0);
    if(list != null) {
        out.writeInt(list.size());
        for(String item: list) {
            out.writeString(item);
        }
    }
}

private X(Parcel in) {
    boolean hasList = in.readInt() > 0;
    if(hasList) {
        int size = in.readInt();
        list = new RealmList<String>(size);
        for(int i = 0; i < size; i++) {
            list.add(in.readString());
        }
    }
}
EpicPandaForce
  • 79,669
  • 27
  • 256
  • 428
  • Works good, but I get empty Array values in db, haha. I did not fully understand your code in K function. What's hasList? Should not I somehow read string array into my RealmList? – MaaAn13 Sep 03 '18 at 15:53
  • That's to handle nullability, that's all. Managed RealmObject cannot have null RealmList, but it's there for sake of completion anyway. Not sure why you'd get empty values though. – EpicPandaForce Sep 03 '18 at 17:01
  • How should I add this field in DbMigration? Variable is defined: @SerialName("ha") var list: @WriteWith RealmList? = null _____________ x.addField("fieldName", //whatType?); – MaaAn13 Sep 04 '18 at 08:45
  • 1
    `addRealmListField("fieldName", String::class.java)` – EpicPandaForce Sep 04 '18 at 09:43