简体   繁体   中英

Use Parcelable with an Object with Hashmap

I have an arrayList of objects stored in a class that extends intentService. It's instance variables for the object are:

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

I want to be able to pass this arrayList back to an Activity. I have read that Parcelable is the way to go when you want to pass objects from a service to an activity. My method for writing to a parcel looks like this:

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

I am not sure how to read the hashmap back in from the parcel though? This question suggested using Bundle but I am unsure what they meant. Any help much appreciated.

If you're implementing Parcelable you need to have a static Parcelable.Creator field called CREATOR that creates your object - see 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];
     }
 };

Then in your constructor that takes a Parcel you need to read the fields you wrote in the same order.

Parcel has a method called readMap(). Note you need to pass a classloader for the type of object in your HashMap. Since yours is storing doubles it might also work with null passed as the ClassLoader. Something like ...

in.readMap(historicFeedData, Double.class.getClassLoader());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM