Skip to content

Instantly share code, notes, and snippets.

@andrewmarmion
Created March 21, 2017 20:08
Show Gist options
  • Save andrewmarmion/09d7342b768b0a0af322005689ed7e96 to your computer and use it in GitHub Desktop.
Save andrewmarmion/09d7342b768b0a0af322005689ed7e96 to your computer and use it in GitHub Desktop.
An example of a class that implements Parcelable
import android.os.Parcel;
import android.os.Parcelable;
public class Person implements Parcelable {
private String name;
private int age;
private String email;
private boolean hasPhone;
// Constuctor
public Person(String name, int age, String email, boolean hasPhone) {
this.name = name;
this.age = age;
this.email = email;
this.hasPhone = hasPhone;
}
// Getters and Setters would go here
// Parcelable Methods go below here
// Private constructor, variable order must match that of writeToParcel
private Person(Parcel in) {
name = in.readString();
age = in.readInt();
email = in.readString();
hasPhone = in.readByte() != 0;
}
@Override
public int describeContents() {
return 0;
}
// Make sure your variables line up in the writeToParcel and the Person(Parcel in) methods.
// They must be in the same order.
@Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeString(name);
parcel.writeInt(age);
parcel.writeString(email);
parcel.writeByte((byte) (hasPhone ? 1: 0));
}
public static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>() {
@Override
public Person createFromParcel(Parcel source) {
return new Person(source);
}
@Override
public Person[] newArray(int size) {
return new Person[size];
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment