我刚刚将项目中的所有可序列化类更改为parcelable类。 一切都工作正常,除了那个由包含另一个ArrayList的ArrayList组成的类。我已经调试过了。 编写此ArrayList时没有错误。但我在阅读时遇到错误。
这是发生错误的类:
public class Timetable implements Parcelable
{
private int actLap = 0;
private ArrayList<Lap> timetable;
private ArrayList<Location> loggedLocations;
private Date startTime; ...
...
public void writeToParcel(Parcel out, int flags)
{
out.writeInt(actLap);
out.writeTypedList(timetable); //no error here
out.writeTypedList(loggedLocations); ...
...
private Timetable(Parcel in)
{
actLap = in.readInt();
in.readTypedList(timetable, Lap.CREATOR); //error after this line
in.readTypedList(loggedLocations, Location.CREATOR);
startTime = (Date)in.readSerializable();
bestLap = in.readParcelable(Lap.class.getClassLoader());
track = in.readParcelable(Track.class.getClassLoader());
description = in.readString();
}
以下是其他课程:
public class Lap implements Parcelable
{
private ArrayList<Time> sectorTimes = new ArrayList<Time>();
private Time laptime; ...
...
public void writeToParcel(Parcel out, int flags)
{
out.writeTypedList(sectorTimes);
out.writeParcelable(laptime,flags);
}
public static final Parcelable.Creator<Lap> CREATOR = new Parcelable.Creator<Lap>()
{
public Lap createFromParcel(Parcel in)
{
return new Lap(in);
}
public Lap[] newArray(int size)
{
return new Lap[size];
}
};
private Lap(Parcel in)
{
in.readTypedList(sectorTimes, Time.CREATOR);
laptime = in.readParcelable(Time.class.getClassLoader());
}
这节课:
public class Time implements Parcelable
{
private long timeLong;
private String timeString;...
...
public void writeToParcel(Parcel out, int flags)
{
out.writeLong(timeLong);
out.writeString(timeString);
}
public static final Parcelable.Creator<Time> CREATOR = new Parcelable.Creator<Time>()
{
public Time createFromParcel(Parcel in)
{
return new Time(in);
}
public Time[] newArray(int size)
{
return new Time[size];
}
};
private Time(Parcel in)
{
timeLong = in.readLong();
timeString = in.readString();
}
就像我已经说过的,一切正常(有更多的Parcelable类,我通过意图(包括一个ArrayList)传递,并保存在文件中)。 那么你们可以帮我写一下双ArrayList吗? 提前致谢
答案 0 :(得分:6)
如果您的代码是已发布的,那么您只是错过了ArrayLists的初始化,即
private Timetable(Parcel in)
{
// readTypeList() needs an existing List<> to load.
timetable = new ArrayList<Lap>();
loggedLocations = new ArrayList<Location>();
actLap = in.readInt();
in.readTypedList(timetable, Lap.CREATOR);
in.readTypedList(loggedLocations, Location.CREATOR);
...