如何使用ArrayList <Parcelable>正确实现Parcelable?

我有麻烦让我的课程Parcelable 。 麻烦的是,我正试图在类中写入一个ArrayList<Parcelable>对象的成员。 ArrayListSerializable ,列表中的对象( ZigBeeDev )是ZigBeeDev

这是相关的代码:

 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]; } }; //... } 

我已经标记了两处“//帮助这里”,以了解如何正确写入包裹以及如何重build它。 如果ZigBeeDevZigBeeDev (正确testing),我该如何正确地做到这一点?

你差不多了!

你只需要做:

 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); } 

就这样!

对于Integer的列表,你也可以这样做:

 out.writeList(_lqis); _lqis = new ArrayList<>(); in.readList(_lqis Integer.class.getClassLoader()); 

它应该工作。

在我的情况in.readTypedList(_devices, ZigBeeDev.CREATOR);_devices上给了我一个NullPointerException 。 所以我用这个:

 _devices = in.createTypedArrayList(ZigBeeDev.CREATOR); 

您应该使用writeList(List l)作为整数列表, writeTypedList(List val)作为ZigBeeDevices的列表

在构造函数中,你应该使用

 _lqis = in.createTypedArrayList(ZigBeeDev.CREATOR); 

并在“writeToParcel”中使用

 out.writeTypedList(_lqis);