Search code examples
javaandroidinterfaceparcelableimplements

Android - Easier/Faster/Less tedious way to implement Parcelable?


Whenever I want my class to implement Parcelable, it always goes down to the same thing. My code always looks like this:

public class MyClass implements Parcelable{

    private String stringA;
    private int intA;
    .
    .
    .

    //## Parcelable code - START ################################
    @Override
    public int describeContents() {
          return this.hashCode();
    }
    @Override
    public void writeToParcel(Parcel dest, int flags) {

     dest.writeString(stringA);
     dest.writeInt(intA);
     .
     .
     .
    }
    public static final Parcelable.Creator<MyClass> CREATOR = new Parcelable.Creator<MyClass>() {

    @Override
    public MyClass createFromParcel(Parcel in) {
            return new MyClass(in); 
    }

    @Override
    public MyClass[] newArray(int size) {
            return new MyClass[size];
    }
    };
    public MyClass(Parcel in){

        this.cancellationnote   = in.readString();
        this.intA = in.readInt();
        .
        .
        .
    }
    //## Parcelable code - END ################################
    }

But that is very repetitive, tedious and error prone. Is there an easier way to do it?


Solution

  • Android Studio 1.3 has now a "Quick Fix" which generates the Parcelable implementation automatically for your class.

    It still, however, puts all the boilerplate code in your own class (but I guess there is no way around it).