I want to pass on object between two activities in Android which has lead me to parcelable classes. I am not trying to convert my current class but don\'t understand the Par
public static final Parcelable.Creator CREATOR =
new Parcelable.Creator() {
public ObjectB createFromParcel(Parcel in) {
return new ObjectB(in);
}
public ObjectB[] newArray(int size) {
return new ObjectB[size];
}
};
This field is needed for Android to be able to create new objects, individually or as arrays. This also means that you can use use the default constructor to create the object and use another method to hyrdate it as necessary.
Look at this Android – Parcelable
Online tool for creating Parcelable class
and http://www.appance.com/tag/parcelable/
Here is a great tool for Android parcelable implementations.
Parcelabler by Dallas Gutauckis
Here is another tool for creating parcelable objects using simple annotations
https://github.com/johncarl81/parceler
Transferring data between activities can be done using serializable as well as Parcelable. But parcelable is considered best.(why)
There is a plugin in android that lets you insert parcelable code for fields in the class. You can find it from menu File > Settings > Plugins > Android parcelable code generator.
And use the shortcut alt + insert just like getter and setter to use the plugin.
On GitHub you can find some code I wrote some time ago for simplifying the handling of Parcelables (e.g. writing to and reading from parcels, simplifying the initializer code for CREATORs).
Writing to a parcel:
parcelValues(dest, name, maxSpeed, weight, wheels, color, isDriving);
where color is an enum and isDriving is a boolean, for example.
Reading from a parcel:
// [...]
color = (CarColor)unparcelValue(CarColor.class.getClassLoader());
isDriving = (Boolean)unparcelValue();
Creating a CREATOR for classes:
public static final Parcelable.Creator<Car> CREATOR =
Parceldroid.getCreatorForClass(Car.class);
...or for enums:
public static final Parcelable.Creator<CarColor> CREATOR =
Parceldroid.getCreatorForEnum(CarColor.class);
Just take a look at the "ParceldroidExample" I added to the project.