How write Java.util.Map into parcel in a smart way?

I ended up doing it a little differently. It follows the pattern you would expect for dealing with Parcelables, so it should be familiar.

public void writeToParcel(Parcel out, int flags){
  out.writeInt(map.size());
  for(Map.Entry<String,String> entry : map.entrySet()){
    out.writeString(entry.getKey());
    out.writeString(entry.getValue());
  }
}

private MyParcelable(Parcel in){
  //initialize your map before
  int size = in.readInt();
  for(int i = 0; i < size; i++){
    String key = in.readString();
    String value = in.readString();
    map.put(key,value);
  }
}

In my application, the order of the keys in the map mattered. I was using a LinkedHashMap to preserve the ordering and doing it this way guaranteed that the keys would appear in the same order after being extracted from the Parcel.


you can try:

bundle.putSerializable(yourSerializableMap);

if your chosen map implements serializable (like HashMap) and then you can use your writeBundle in ease