I am having trouble making my class Parcelable. The trouble is, I am trying to write to the parcel a member in the class which is an ArrayList object. The ArrayList is serializable, and the objects (ZigBeeDev) in the list are Parcelable.
在使用Parcelable的过程中,我需要实例化一个ArrayList对象,下面是代码:
package com.gnychis.coexisyst;
import java.util.ArrayList;
import java.util.Iterator;
import android.os.Parcel;
import android.os.Parcelable;
public class ZigBeeNetwork implements Parcelable {
public String _mac; // the source address (of the coordinator?)
public String _pan; // the network address
public int _band; // the channel
ArrayList<Integer> _lqis; // link quality indicators (to all devices?)
ArrayList<ZigBeeDev> _devices; // the devices in the network
public void writeToParcel(Parcel out, int flags) {
out.writeString(_mac);
out.writeString(_pan);
out.writeInt(_band);
out.writeSerializable(_lqis);
out.writeParcelable(_devices, 0); // help here
}
private ZigBeeNetwork(Parcel in) {
_mac = in.readString();
_pan = in.readString();
_band = in.readInt();
_lqis = (ArrayList<Integer>) in.readSerializable();
_devices = in.readParcelable(ZigBeeDev.class.getClassLoader()); // help here
}
public int describeContents() {
return this.hashCode();
}
public static final Parcelable.Creator<ZigBeeNetwork> CREATOR =
new Parcelable.Creator<ZigBeeNetwork>() {
public ZigBeeNetwork createFromParcel(Parcel in) {
return new ZigBeeNetwork(in);
}
public ZigBeeNetwork[] newArray(int size) {
return new ZigBeeNetwork[size];
}
};
//...
}但是上面的代码是错误的,下面给出解决方法:
public void writeToParcel(Parcel out, int flags) {
out.writeString(_mac);
out.writeString(_pan);
out.writeInt(_band);
out.writeSerializable(_lqis);
out.writeTypedList(_devices);
}
private ZigBeeNetwork(Parcel in) {
_mac = in.readString();
_pan = in.readString();
_band = in.readInt();
_lqis = (ArrayList<Integer>) in.readSerializable();
in.readTypedList(_devices, ZigBeeDev.Creator);
}That's all!
For your list of Integer, you can also do :
out.writeList(_lqis);
in.readList(_lqis Integer.class.getClassLoader());这个是我在Stackoverflow上面找到的。
本文详细介绍了如何在Android中实现自定义类的Parcelable接口,特别是在处理ArrayList类型的成员变量时的正确做法。通过对比错误和正确的代码示例,帮助读者理解如何正确地在Parcel中写入和读取数据。
835

被折叠的 条评论
为什么被折叠?



