0

I m using a Map of String and Pojo. I m implementing Parcelable in that class. To generate parcelable I m using plugin Android Parcelable code generator by Michal Charmas. It's working fine for everything else, but not for Map<String, Object>. Here is my code

 @Override
    public void writeToParcel(Parcel dest, int flags) {

        dest.writeInt(this.driverDocuments.size());
        for (Map.Entry<String, Document> entry : this.driverDocuments.entrySet()) {
            dest.writeString(entry.getKey());
            dest.writeSerializable(entry.getValue());
        }
    } 

Off course if the map is null, it will throw null pointer. But if we apply the null check, it will miss the map when it's null. So I'm thinking of the proper recommended way to parcel Map. Anyone suggestion ?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Nouman Ghaffar
  • 3,780
  • 1
  • 29
  • 37

1 Answers1

0

I found the solution, In case anyone else needs help Here is the working code, where my Map is of Map<String,Document> where Document is another Pojo.

@Override
public void writeToParcel(Parcel dest, int flags) {

    dest.writeByte((byte) (driverDocuments == null ? 0x00 : 0x01));
    if (driverDocuments != null) {
        dest.writeInt(this.driverDocuments.size());
        for (Map.Entry<String, Document> entry : this.driverDocuments.entrySet()) {
            dest.writeString(entry.getKey());
            dest.writeSerializable(entry.getValue());
        }
    }
}

and

 protected Model(Parcel in) {

    if (in.readByte() == 0X01) {
        int documentSize = in.readInt();
        this.driverDocuments = new HashMap<String, Document>(documentSize);
        for (int i = 0; i < documentSize; i++) {
            String key = in.readString();
            Document value = (Document) in.readSerializable();
            this.driverDocuments.put(key, value);
        }
    } else
        driverDocuments = null;
}
Nouman Ghaffar
  • 3,780
  • 1
  • 29
  • 37