如何打包RealmList <string>?

时间:2018-09-03 13:58:07

标签: android realm

我有一个要打包然后放入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?  
}

我不确定如何writeToParcelreadToParcel RealmList?

1 个答案:

答案 0 :(得分:1)

您可以通过写出其大小然后重新构建来将其变为Parcelable。

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