Карта Parcelable надлежащим образом? - PullRequest
0 голосов
/ 04 марта 2019

Я использую Map из String и Pojoimplementing Parcelable в этом class.Для генерации parcelable я использую плагин Android Parcelable code generator от Michal Charmas .Работает нормально для всего остального, но не для Map<String, Object>.Вот мой код

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

Конечно, если карта нулевая, будет выброшен нулевой указатель.Но если мы применим нулевую проверку, она пропустит карту, когда будет null.Поэтому я думаю о правильном рекомендованном способе посылки карты.Есть предложения?

1 Ответ

0 голосов
/ 04 марта 2019

Я нашел решение, на случай, если кому-то еще понадобится помощь. Вот рабочий код, где мой Map имеет значение Map<String,Document>, где Документ - это другое 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());
        }
    }
}

и * 1007.*

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