Reputation: 11741
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?
Upvotes: 2
Views: 519
Reputation: 11113
Using Parceler, you simply have to annotate your bean with @Parcel
and use the Parcels
utility class to wrap/unwrap when you want to use the bean as a Parcelable
:
@Parcel
public class MyClass {
String stringA;
int intA;
}
Be sure to make your fields non-private if you're using the default FIELD
sealization strategy.
The Parcels utility class usage:
intent.putExtra("example", Parcels.wrap(myClass));
//...
Example example = MyClass .unwrap(getIntent().getParcelableExtra("example"));
To import Parceler in Gradle, add the following lines along with the apt plugin:
compile "org.parceler:parceler-api:1.0.3"
apt "org.parceler:parceler:1.0.3"
In my book this is the easiest / less tedious way to use Parcelables in Android.
Upvotes: 0
Reputation: 11741
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).
Upvotes: 0
Reputation: 2096
There is an easier way by using "Parcelabler" by Dallas Gutauckis. It generates the code automatically for your class:
Still, it doesn't make the code any shorter.
Upvotes: 1