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

Kitesurfer picture Kitesurfer · Nov 24, 2011 · Viewed 35.1k times · Source

I have a Generic Map of Strings (Key, Value) and this field is part of a Bean which I need to be parcelable. So, I could use the Parcel#writeMap Method. The API Doc says:

Please use writeBundle(Bundle) instead. Flattens a Map into the parcel at the current dataPosition(), growing dataCapacity() if needed. The Map keys must be String objects. The Map values are written using writeValue(Object) and must follow the specification there. It is strongly recommended to use writeBundle(Bundle) instead of this method, since the Bundle class provides a type-safe API that allows you to avoid mysterious type errors at the point of marshalling.

So, I could iterate over each Entry in my Map a put it into the Bundle, but I'm still looking for a smarter way doing so. Is there any Method in the Android SDK I'm missing?

At the moment I do it like this:

final Bundle bundle = new Bundle();
final Iterator<Entry<String, String>> iter = links.entrySet().iterator();
while(iter.hasNext())
{
    final Entry<String, String>  entry =iter.next();
    bundle.putString(entry.getKey(), entry.getValue());
}
parcel.writeBundle(bundle);

Answer

Anthony Naddeo picture Anthony Naddeo · Jan 12, 2013

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.