-
Notifications
You must be signed in to change notification settings - Fork 24
@Parcelable
@Parcelable
lets you automatically turn any class into a Parcelable object.
It will pick every parcelable or serializable attribute of the annotated class and put it into a Parcel
object, just like you would have to do implementing the Parcelable interface.
public void writeToParcel(Parcel parcel, int flags)
public int describeContents()
public static Parcelable.Creator CREATOR
// Constructor to create a MyClass instance from a Parcel object
public MyClass(Parcel source)
Also, it will create a MyClass.Creator
class which will implement Parcelable.Creator
for you.
Just add @Parcelable
annotation to the class you want to use as a Parcelable object.
Even having only a few classes, you can end up having circular dependencies, where having two parcelable classes A and B, A contains a B instance and B contains an A instance. If you used @Parcelable with them both your app would go crazy while trying to save them as it will end on a never-ending cycle. What to do here? Use
exclude
parameter on the annotation.
If there is some attribute that you don't want parceled, you can explicitly do that using the exclude
parameter on the annotation like this:
@Parcelable(exclude={anotherObject;andThisToo})
class ParcelableClass {
...
ParcelableClass anotherObject
SomeOtherClass andThisToo
@Parcelable
class ParcelableClass {
int id
String name
}
Will generate:
class ParcelableClass implements Parcelable {
...
public ParcelableClass(Parcel source) {
this.id = source.readInt()
this.name = source.readString()
}
public void writeToParcel(Parcel out) {
out.writeInt(id)
out.writeString(name)
}
...
As previously said, @Parcelable
will only parcel what can be put into a Parcel
object. This classes are:
- String
- String[]
- List
- Map
- SparseArray
- Parcelable
- Parcelable[]
- Bundle
- CharSequence
- Serializable
Of course, any other primitive variable (int, long, float, char, etc.) can be parceled too, as well as arrays (int[], double[]...).
Also, please take in mind that static
variables won't be parceled as they don't belong to a single instance.