Question

I have classes like this.

public class RateData  {
    Map<String, List<RateDTO>> rateMap;
}

public class RateDTO {

     private String code;

     private String name;

     private String value;
}

Now I need parcelable this RateData class. I think we can not parcel this rateMap as normal variable.

Please give me an example how to do this.

Was it helpful?

Solution

You should make DateRTO Parcelable - this should be trivial. Then,

Map<String, List<RateDTO>> map;

public void writeToParcel(Parcel out, int flags) {
    out.writeInt(map.size());

    for (Map.Entry<String, List<RateDTO>> entry : map.entrySet()) {
        out.writeString(entry.getKey());

        final List<RateDTO> list = entry.getValue();
        final int listLength = list.size();

        out.writeInt(listLength);

        for (RateDTO item: list) {
            out.writeParcelable(item, 0);
        }
    }
}

private MyParcelable(Parcel in) {
    final int size = in.readInt();

    for (int i = 0; i < size; i++) {
        final String key = in.readString();
        final int listLength = in.readInt();

        final List<RateDTO> list = new ArrayList<RateDTO>(listLength);
        for (int j = 0; j < listLength; j++) {
            final RateDTO value = in.readParcelable(ParentClass.class.getClassLoader());
            list.add(value);
        }

        map.put(key, list);
    }
}

I haven't tested the code, but I believe it should be close to OK. Note that this solution is not particularly good if your map is relatively large.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top