Android Class Parcelable with ArrayList

If you need to pass an ArrayList between activities, then I’d go with implementing Parcelable also, as there is no other way around I guess.
However I don’t think you will need that much of getters and setters. Here is your Question class which implements Parcelable:

public class Question implements Parcelable {
    public String id;
    public String text;
    public String image;
    public ArrayList<Choice> choices;


    /**
     * Constructs a Question from values
     */
    public Question (String id, String text, String image, ArrayList<Choice> choices) {
        this.id = id;
        this.text = text;
        this.image = image;
        this.choices = choices;
    }

    /**
     * Constructs a Question from a Parcel
     * @param parcel Source Parcel
     */
    public Question (Parcel parcel) {
        this.id = parcel.readString();
        this.text = parcel.readString();
        this.image = parcel.readString();
        this.choices = parcel.readArrayList(null);
    }

    @Override
    public int describeContents() {
        return 0;
    }

    // Required method to write to Parcel
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(id);
        dest.writeString(text);
        dest.writeString(image);
        dest.writeList(choices);
    }

    // Method to recreate a Question from a Parcel
    public static Creator<Question> CREATOR = new Creator<Question>() {

        @Override
        public Question createFromParcel(Parcel source) {
            return new Question(source);
        }

        @Override
        public Question[] newArray(int size) {
            return new Question[size];
        }

    };
}

Leave a Comment