【问题标题】:Use Parcelable with an Object with Hashmap将 Parcelable 与带有 Hashmap 的对象一起使用
【发布时间】:2013-09-19 08:48:41
【问题描述】:

我有一个存储在扩展 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,但我不确定它们的含义。非常感谢任何帮助。

【问题讨论】:

    标签: java android arraylist hashmap intentservice


    【解决方案1】:

    如果您正在实施 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());
    

    【讨论】:

    • 感谢 DEnizmveli 的回答,但我有一个问题,我认为您可以提供帮助。我有 ArrayList> 我想将其写入包裹,然后在下一个活动中读取它。你能指导一下怎么做吗?
    猜你喜欢
    • 2017-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-20
    • 2016-09-23
    相关资源
    最近更新 更多