+-
使用带有Hashmap的对象的Parcelable
我有一个存储在类中的对象的arrayList,它扩展了intentService.它的对象的实例变量是:

int id;
String name;
HashMap<Long, Double> historicFeedData

我希望能够将此arrayList传递回Activity.我已经读过,当您想要将对象从服务传递到活动时,可以使用Parcelable.我写入包裹的方法如下:

public void writeToParcel(Parcel out, int flags) {
     out.writeInt(id);
     out.writeString(name);
     dest.writeMap(historicFeedData);
 }

我不知道如何从包裹中读回哈希图? This question建议使用Bundle,但我不确定它们是什么意思.任何帮助非常感谢.

最佳答案
如果您正在实现 Parcelable,则需要一个名为CREATOR的静态Parcelable.Creator字段来创建您的对象 – 请参阅doco RE createFromParcel()

 public static final Parcelable.Creator<MyParcelable> CREATOR
         = new Parcelable.Creator<MyParcelable>() {
     public MyParcelable createFromParcel(Parcel in) {
         return new MyParcelable(in);
     }

     public MyParcelable[] newArray(int size) {
         return new MyParcelable[size];
     }
 };

然后在你的构造函数中,你需要读取你以相同顺序编写的字段.

Parcel有一个名为readMap()的方法.请注意,您需要为HashMap中的对象类型传递类加载器.由于你的存储双打,它也可以作为ClassLoader传递null.就像是 …

in.readMap(historicFeedData, Double.class.getClassLoader());
点击查看更多相关文章

转载注明原文:使用带有Hashmap的对象的Parcelable - 乐贴网