java - 包含自定义对象的 Parcelable 列表

标签 java android parcelable

我正在尝试在 Android 上的 Activities 之间传递数据 (ArrayList)

当实现 Parcelable 的类不包含自定义对象(商店)时一切正常,但如果我的类包含自定义对象,我该怎么办?

购物

public Shop(Parcel in) {
    this.id  = in.readString();
    this.name = in.readString();
    this.type = in.readString();
    this.lat= in.readDouble();
    this.long= in.readDouble();
}
@Override
public void writeToParcel(Parcel dest, int flags) {

    dest.writeString(this.id);
    dest.writeString(this.name);
    dest.writeString(this.type);
    dest.writeDouble(this.lat);
    dest.writeDouble(this.long);
}

@SuppressWarnings("rawtypes")
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
    public Shop createFromParcel(Parcel in) {
        return new Shop(in);
    }

    public Shop[] newArray(int size) {
        return new Shop[size];
    }
};

这是我的另一个类 Offer,它包含一个 Shop 对象

public Offer(Parcel in) {
    this.id  = in.readInt();
    this.title = in.readString();
    this.myShop = in.read.......();
}


@Override
public void writeToParcel(Parcel dest, int flags) {

    dest.writeInt(this.id);
    dest.writeString(this.title);
    dest.write......(this.myShop);
} 

我应该读写哪种数据类型?

非常感谢!

最佳答案

您的Shop 类应该实现Parcelable 并且您应该使用

public Offer(Parcel in) {
    this.id  = in.readInt();
    this.title = in.readString();
    this.myShop = in.readParcelable(Shop.class.getClassLoader());
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeInt(this.id);
    dest.writeString(this.title);
    dest.writeParcelable(this.myShop, flags);
}

关于java - 包含自定义对象的 Parcelable 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21551167/

相关文章:

java - Ant 编译: unclosed character literal

c# - 桌面应用程序的推送通知?

java - JSON 数组获取长度

Android ksoap2 https 连接

java - 解码错误时未找到类。可使用 byteArray、byte[] 进行解析

java - 调整Gridbag布局

Android:通过 http 加载多个位图/缩略图的最快方法是什么?

android - Google 是否停止支持 Android Eclipse 插件?

Android:在带有 ArrayList<customObject> 的类中使用 Parcelable 接口(interface)时出现 nullPointerException

java - Parcelable 对象在接收 Activity 中为 Null,在其他 Activity 中为 Good