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
If both the key
and value
of the map extend Parcelable
, you can have a pretty nifty Generics solution to this:
Code
// For writing to a Parcelpublic <K extends Parcelable,V extends Parcelable> void writeParcelableMap( Parcel parcel, int flags, Map<K, V > map){ parcel.writeInt(map.size()); for(Map.Entry<K, V> e : map.entrySet()){ parcel.writeParcelable(e.getKey(), flags); parcel.writeParcelable(e.getValue(), flags); }}// For reading from a Parcelpublic <K extends Parcelable,V extends Parcelable> Map<K,V> readParcelableMap( Parcel parcel, Class<K> kClass, Class<V> vClass){ int size = parcel.readInt(); Map<K, V> map = new HashMap<K, V>(size); for(int i = 0; i < size; i++){ map.put(kClass.cast(parcel.readParcelable(kClass.getClassLoader())), vClass.cast(parcel.readParcelable(vClass.getClassLoader()))); } return map;}
Usage
// MyClass1 and MyClass2 must extend ParcelableMap<MyClass1, MyClass2> map;// Writing to a parcelwriteParcelableMap(parcel, flags, map);// Reading from a parcelmap = readParcelableMap(parcel, MyClass1.class, MyClass2.class);