我有一个有服务和活动的应用程序。我的基类和列表类正在实现parcelable。 list类使用writeTypedList()/ readTypedList()来包裹自定义列表。但是,当检索列表时,我得到了正确数量的元素,但在尝试访问除列表的第一个元素之外的任何元素时,我得到一个空指针异常。在执行writeToParcel()时,我可以看到添加了2个具有正确数据的元素,但是当执行readFromParcel()时,只显示第一个元素,第二个元素为null。
任何帮助将不胜感激!!!
这是我的列表容器类:
public class WfdDeviceList implements Parcelable {
private static final String TAG = "WfdDeviceList";
public List<WfdDevice> devList;
public WfdDeviceList() { devList = new ArrayList<WfdDevice>(); }
public WfdDeviceList(Parcel parcel) {
this();
readFromParcel(parcel);
}
public void clear() {
devList.clear();
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int flags) {
Log.d(TAG, "writeToParcel(): " + devList.size());
Log.d(TAG, "flags: " + flags);
for (WfdDevice device : devList) {
Log.d(TAG, "Writing: " + device.name);
}
parcel.writeTypedList(devList);
}
public void readFromParcel(Parcel parcel) {
Log.d(TAG, "readFromParcel()");
parcel.readTypedList(devList, WfdDevice.CREATOR);
Log.d(TAG, "Size: " + devList.size());
WfdDevice device = devList.get(0);
Log.d(TAG, "Device1: " + device.name);
}
public static final Parcelable.Creator<WfdDeviceList> CREATOR = new Parcelable
.Creator<WfdDeviceList>() {
public WfdDeviceList createFromParcel(Parcel in) {
return new WfdDeviceList(in);
}
public WfdDeviceList[] newArray(int size) {
return new WfdDeviceList[size];
}
};
}
public class WfdDevice implements Parcelable {
public String macAddress;
public String name;
public WfdDeviceType type;
public String ipAddr;
public String pin;
public boolean isConnected;
public WfdDevice() {}
public WfdDevice(Parcel parcel) {
readFromParcel(parcel);
}
@Override
public int describeContents() {
return 0;
}
WfdDeviceType getType(int type) {
switch(type) {
case 1:
return WfdDeviceType.source;
case 2:
return WfdDeviceType.primarySink;
case 3:
return WfdDeviceType.secondarySink;
case 4:
return WfdDeviceType.sourcePrimarySink;
default:
case 0:
return WfdDeviceType.unknown;
}
}
@Override
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeString(this.macAddress);
parcel.writeString(this.name);
parcel.writeInt(type.ordinal());
parcel.writeString(this.ipAddr);
parcel.writeString(this.pin);
parcel.writeInt(this.isConnected == true ? 1 : 0);
}
public void readFromParcel(Parcel parcel) {
this.macAddress = parcel.readString();
this.name = parcel.readString();
this.type = getType(parcel.readInt());
this.ipAddr = parcel.readString();
this.pin = parcel.readString();
this.isConnected = (parcel.readInt() == 1 ? true : false);
}
public static final Parcelable.Creator<WfdDevice> CREATOR = new Parcelable
.Creator<WfdDevice>() {
public WfdDevice createFromParcel(Parcel in) {
return new WfdDevice(in);
}
public WfdDevice[] newArray(int size) {
return new WfdDevice[size];
}
};
}
答案 0 :(得分:1)
我想我已经找到了这个问题。似乎在我的WfdDevice类中使用枚举类型WfdDeviceType会以某种方式导致问题。我已经将这种类型从枚举改为int,问题已经消失。