0

I haven't found a proper answer on the stackoverflow on the same and confused on how to achieve the right Parcelable implementation for an Map .

I suppose for a Map< String , String > below is the correct implementation:

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);
  }
}

But what about Map < String , Object > ?

David Wasser
  • 93,459
  • 16
  • 209
  • 274

1 Answers1

0

You can't. Because you can't serialize an Object into a Parcel. If the Object in question implements Parcelable then you can do something like this:

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

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

HOWEVER: You don't need to do this, because the Parcel class already knows how to serialize and unserialize Map , provided that the key is a String and the value is a "known" object type (includes Serializable and Parcelable). So you can just do this:

public void writeToParcel(Parcel out, int flags){
    out.writeValue(map);
}


private MyParcelable(Parcel in){
    map = (Map)in.readValue(getClass().getClassLoader());
}

See https://developer.android.com/reference/android/os/Parcel.html#writeValue(java.lang.Object) for a list of "known" object types.

NOTE: You will get always get a HashMap if you call Parcel.getValue() on a Map. Android is stupid about this and assumes all Maps are HashMaps.

David Wasser
  • 93,459
  • 16
  • 209
  • 274
  • Hi @David , thanks for the answer. i tried the first code snippet but it didn't work for me. Also i am confused on how to use the second snippet u shared, map = in.readValue(getClass().getClassLoader()); is not a valid statement according to android studio. – akshat tailang Nov 09 '18 at 16:26
  • What do you mean by "didn't work". Be more specific please. Remote debugging is hard enough without details – David Wasser Nov 09 '18 at 17:13
  • Reagding "not a valid statement", you probably need to cast the returned value. I've updated my answer. – David Wasser Nov 10 '18 at 18:47