Use Parcelable with an Object Using a Hashmap

I have an array of List objects stored in a class that extends aimService. These are the instance variables for the object:

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

I want this array to return to Activity. I read that Parcelable is the way to go when you want to transfer objects from a service to an action. My method of writing on the premise 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 map back from the package? This question suggested using the Bundle, but I'm not sure what they meant. Any help is greatly appreciated.

+4
source share
1 answer

If you are 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 the package, you need to read the fields that you wrote in the same order.

The package has a method called readMap (). Note that you need to pass the class loader for the type of the object in your HashMap. Since yours keeps doubling, it can also work with null passed as ClassLoader. Sort of...

 in.readMap(historicFeedData, Double.class.getClassLoader()); 
+6
source

Source: https://habr.com/ru/post/1502216/


All Articles