We can pass primitive data between Activities such as Integer, String, Booleans, etc. In this article, we are gonna see the world of Parcelable interface available for Android to pass objects between the activities.
We will be using the very basic Person class containing two fields,
- The name of the Person
- The age of the Person
Make sure this class implements the Parcelable interface which helps in serializing and deserializing the Person object on Activity/Fragments start or stop.
public class Person implements Parcelable { private String name; private int age; . . .
Next steps will be implementing few housekeeping methods of Parcelable interface, which in general, stays the same.
public static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>() { public Person createFromParcel(Parcel in) { return new Person(in); } public Person[] newArray(int size) { return new Person[size]; } }; @Override public int describeContents() { return 0; }
The static CREATOR class creates your object from a Parcel via the createFromParcel method that takes in a parcel and passes it to a constructor in your class that does the grunt work.
The newArray method allows an array of your objects to be parcelled.
The describeContents method is generally not used. Some information about its possible uses are here: http://stackoverflow.com/questions/4076946/parcelable-where-when-is-describecontents-used/4914799#4914799
Note: We don’t need to call the above methods. They’re used internally by Android in most cases.
Finally, the writeToParcel method writes your fields to a parcel in a particular order.
@Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(name); dest.writeInt(age); }
Then the constructor with a Parcel argument gets them back out in that order:
private Person(Parcel in) { name = in.readString(); age = in.readInt(); }
Now you can use this object where ever you can use a Parcelable. For instance, passing arguments to Bundles:
Bundle outState = new Bundle(); outState.putParcelable("someId", new Person()); fragment.setArguments(outState); // Load the fragment