johncarl81 / parceler

:package: Android Parcelables made easy through code generation.
http://parceler.org
Apache License 2.0
3.56k stars 273 forks source link

Parceler fails when used with with Lifecycle-viewmodel 2.2.0 #382

Closed LNdame closed 4 years ago

LNdame commented 4 years ago

Description

Bumping from androidx.lifecycle:lifecycle-viewmodel:2.0.0 to androidx.lifecycle:lifecycle-viewmodel:2.2.0 casuse the following issue Parceler: Unable to find read/write generator for type java.util.Map<java.lang.String, java.lang.Object> for androidx.lifecycle.ViewModel.mBagOfTags

mBagsofTags is a private field that is in the lifecycle.ViewModel private final Map<String, Object> mBagOfTags = new HashMap<>();

Resolution attempt

Creating a custom converter for the field was unfruitful as the field is private


    @Override
    public void mapKeyToParcel(String key, Parcel parcel) {
        parcel.writeParcelable(Parcels.wrap(key),0);
    }

    @Override
    public void mapValueToParcel(Object value, Parcel parcel) {
        parcel.writeParcelable(Parcels.wrap(value),0);
    }

    @Override
    public String mapKeyFromParcel(Parcel parcel) {
        return Parcels.unwrap(parcel.readParcelable(java.lang.String.class.getClassLoader()));
    }

    @Override
    public Object mapValueFromParcel(Parcel parcel) {
        return Parcels.unwrap(parcel.readParcelable(java.lang.Object.class.getClassLoader()));
    }
}
johncarl81 commented 4 years ago

What object are you annotating with @Parcel?

sup-fmarais commented 4 years ago

Different person, same project :) I have done some digging and I am pretty sure this is our culprit.

@Parcel
public class DataManagerCachedDataImpl extends ViewModel
        implements DataManagerCachedData {

Do you have some insight into a workaround we could use?

johncarl81 commented 4 years ago

Hi @maraisf! Parceler will attempt to serialize everything, including data members of the inherited classes. I'd recommend avoiding extending things like the ViewModel (which probably has a `Map<String, Object> field) if possible.

sup-fmarais commented 4 years ago

Thanks for the quick response and guidance! 👍

johncarl81 commented 4 years ago

Sure @maraisf, does this solve your issue?

sup-fmarais commented 4 years ago

Removing the extends ViewModel does infact resolve the error above. Thanks.

johncarl81 commented 4 years ago

Cool. You could also use the analyze parameter include or exclude ViewModel from the generated Parcelable, but, generally, I'd recommend keeping the type hierarchy limited.