Challenge 1: Saving State

Here is my solution for the first challenge of Chapter 31. My idea is to make Box class parcelable. To do this the Parcelable interface demands to implement following methods:

Firstly add implements Parcelable:

public class Box implements Parcelable

Next add required fields and methods:

public int describeContents() {
    return 0;

public void writeToParcel(Parcel dest, int flags) {
    mOrigin.writeToParcel(dest, flags);
    mCurrent.writeToParcel(dest, flags);

// This is used for creating new box from Parcel object in createFromParcel function below
private Box (Parcel in) {

public static final Parcelable.Creator<Box> CREATOR = new Parcelable.Creator<Box>() {
     * Return a new box from the data in the specified parcel.
    public Box createFromParcel(Parcel in) {
        Box b = new Box(in);
        return b;

     * Return an array of boxes of the specified size.
    public Box[] newArray(int size) {
        return new Box[size];

After that in the BoxDrawingView implement required methods:

protected Parcelable onSaveInstanceState() {
    // Get state of the parent;
    Parcelable parentState = super.onSaveInstanceState();

    Bundle bundle = new Bundle();
    bundle.putParcelable(PARENT_STATE_KEY, parentState);
    bundle.putParcelableArray(BOXEN_KEY, mBoxen.toArray(new Box[mBoxen.size()]));

    return bundle;

protected void onRestoreInstanceState(Parcelable state) {
    if (state != null && state instanceof Bundle) {
        Bundle bundle = (Bundle) state;


        Box[] boxes = (Box[]) bundle.getParcelableArray(BOXEN_KEY);
        mBoxen = new ArrayList<>(Arrays.asList(boxes));
    } else {

Im not sure if in method onRestoreInstanceState this if statement is required and the place where I’m calling super.onRestoreInstance is also good, but it works.

Looks great! Nice work.

If it were me, I’d drop the if statement in onRestoreInstanceState. You can assume that the state you get back is the state you saved (that’s what all of the classes in the framework do if I remember correctly).