Is it possible to create a Parcelable Class that has an empty constructor?

Viewed 530

I'm trying to use firestore recycler adapter with a parcelable class, but it needs to have an empty constructor.

My solution now is to create a regular class with an empty constructor and right after fetching the data, I'll map the objects into a parcelable copy.

But is it possible to create a Parcelable Class with an empty constructor? In Android Studio when I do right click -> Generate -> I see no secondary constructor option so I guess it's not possible, right?

1 Answers

Yes, it is possible. The Parcelable object will be serialized and deserialized without any problem.

In Android Studio when I do right click -> Generate -> I see no secondary constructor option so I guess it's not possible, right?

No, the fact that it doesn't appear as suggestion in Android Studio code completion feature doesn't mean it is not possible.

Taking as a reference the Parcelable implementation from Android documentation. You should then need to add an empty constructor. Just write the code, don't use code generator.

public MyParcelable(){
}

The class then should look like this:

public class MyParcelable implements Parcelable {
    private int mData;

    public int describeContents() {
        return 0;
    }

    public void writeToParcel(Parcel out, int flags) {
        out.writeInt(mData);
    }

    public static final Parcelable.Creator<MyParcelable> CREATOR
         = new Parcelable.Creator<MyParcelable>() {
        public MyParcelable createFromParcel(Parcel in) {
         return new MyParcelable(in);
        }

        public MyParcelable[] newArray(int size) {
         return new MyParcelable[size];
        }
    };

    private MyParcelable(Parcel in) {
        mData = in.readInt();
    }

    public MyParcelable(){
    }
}
Related