本文介绍了如何正确实现Parcelable有一个ArrayList< Parcelable>?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有让我的班Parcelable麻烦。麻烦的是,我想写的包裹中是一个ArrayList对象的类成员。该ArrayList的是序列化,并在列表中的对象(ZigBeeDev)是Parcelable。

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.

下面是相关code:

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

    //...
}

我标志着两个点//这里帮助,了解如何正确地写入包裹和如何重建它。如果ZigBeeDev是Parcelable(适当的测试),我该怎么做这个正常吗?

I have marked two spots "// help here" to understand how to properly write to the parcel and how to reconstruct it. If ZigBeeDev is Parcelable (properly tested), how do I do this properly?

推荐答案

您几乎得到了它!

您只需要做的:

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);
_lqis = new ArrayList<>();
in.readList(_lqis Integer.class.getClassLoader());

这应该工作。

It should work.

这篇关于如何正确实现Parcelable有一个ArrayList&LT; Parcelable&GT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-20 15:02