Java – Use Parcelable with objects with Hashmaps

Use Parcelable with objects with Hashmaps… here is a solution to the problem.

Use Parcelable with objects with Hashmaps

I have an array list of objects, stored in a class that extends intentService. Its object instance variable is:

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

I want to be able to pass this arrayList back to the Activity. I’ve read that Parcelable is a method when you want to pass an object from a service to an activity. My method of writing the package is as follows:

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

I’m not sure how to read the hash chart back from the package, though? This question suggests using bundles, but I’m not sure what they mean. Any help is greatly appreciated.

Solution

If you are implementing Parcelable You need to have a static Parcelable.Creator field named CREATOR to create 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 the

constructor that takes Parcel, you need to read the fields you wrote in the same order.

Parcel has a method called readMap(). Note that you need to pass a classloader for the object type in the HashMap. Since you are storing doubles, it can also be used with null passed as a ClassLoader. Like….

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

Related Problems and Solutions