[英]How to pass a custom object with a 2D ArrayList field using Parcelable
Inside my Exercise class, I have a 2D ArrayList. 在我的Exercise类中,我有一个2D ArrayList。 I have managed to pass all of the fields from Activity to another using Parcelable. 我设法使用Parcelable将所有字段从Activity传递到另一个字段。 However, I cannot figure out how to pass the 2D ArrayList within my object using Parcelable. 但是,我无法弄清楚如何使用Parcelable在对象内传递2D ArrayList。
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);
// ?????
}
}
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: 正如doc所述,这是因为:
The given class loader will be used to load any enclosed Parcelables. 给定的类加载器将用于加载任何封闭的Parcelables。
Managed to solve the problem myself. 设法自己解决问题。 Thanks. 谢谢。
...
private Exercise(Parcel in) {
...
sets = in.readArrayList(ArrayList.class.getClassLoader());
}
@Override
public void writeToParcel(Parcel dest, int flags) {
...
dest.writeList(sets);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.