Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a custom object with a 2D ArrayList field using Parcelable

Inside my Exercise class, I have a 2D ArrayList. I have managed to pass all of the fields from Activity to another using Parcelable. However, I cannot figure out how to pass the 2D ArrayList within my object using Parcelable.

public class Exercise implements Parcelable{
    private String name, equipmentRequired;
    private ArrayList musclesWorked;
    private HashMap personalBest;
    private boolean selected;
    private float minAccelLevel, minAccelChanges;
    private ArrayList<ArrayList<Double>> sets = new ArrayList<>();

    ...

    private Exercise(Parcel in) {
        name = in.readString();
        equipmentRequired = in.readString();
        musclesWorked = in.readArrayList(ArrayList.class.getClassLoader());
        personalBest = in.readHashMap(HashMap.class.getClassLoader());
        selected = in.readInt() != 0;
        // sets = ???????
    }

    public static final Parcelable.Creator<Exercise> CREATOR = newParcelable.Creator<Exercise>() {
        public Exercise createFromParcel(Parcel in) {
            return new Exercise(in);
        }

        public Exercise[] newArray(int size) {
            return new Exercise[size];
        }
    };

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeString(equipmentRequired);
        dest.writeList(musclesWorked);
        dest.writeMap(personalBest);
        dest.writeInt(selected ? 1 : 0);
        // ?????
    }

}
like image 704
kmtchl Avatar asked Dec 11 '25 05:12

kmtchl


1 Answers

According to Google Documentation and this other question, I would suggest going with

private Exercise(Parcel in) {
        name = in.readString();
        equipmentRequired = in.readString();
        musclesWorked = in.readArrayList(ArrayList.class.getClassLoader());
        personalBest = in.readHashMap(HashMap.class.getClassLoader());
        selected = in.readInt() != 0;
        sets = in.readArrayList(null);
}

This would be because, as the doc states:

The given class loader will be used to load any enclosed Parcelables.

like image 187
Olaia Avatar answered Dec 12 '25 19:12

Olaia



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!