Android implement Parcelable object which has hashmap

♀尐吖头ヾ 提交于 2019-12-11 02:40:06

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/22498746/android-implement-parcelable-object-which-has-hashmap

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