Implement the Parcelable
interface in your custom object and transmit it via an Intent
.
Here is an example of a Parcelable
object.
public class MyObject implements Parcelable {
private String someString = null;
private int someInteger = 0;
public MyObject() {
// perform initialization if necessary
}
private MyObject(Parcel in) {
someString = in.readString();
someInteger = in.readInt();
}
public static final Parcelable.Creator<MyObject> CREATOR =
new Parcelable.Creator<MyObject>() {
@Override
public MyObject createFromParcel(Parcel source) {
return new MyObject(source);
}
@Override
public MyObject[] newArray(int size) {
return new MyObject[size];
}
};
// Getters and setters
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(someString);
dest.writeInt(someInteger);
}
}
Here is what happens. If you implement the Parcelable
interface you have to create a private constructor which takes a Parcel
as a parameter. That Parcel
holds all the serialized values.
You must implement the nested class Parcelable.Creator
with the name CREATOR
as this is going to be called by Android when recreating your object.
The method describeContents()
is only of use in special cases. You can leave it as it is with a return value of 0
.
The interesting action happens in writeToParcel()
where you, as the name tells, write your data to a Parcel
object.
Now you can just add your custom object directly to an Intent
like in this example.
MyObject myObject = new MyObject();
Intent i = new Intent();
i.setExtra("MY_OBJECT", myObject);
// implicit or explicit destination declaration
startActivity(i);