gpt4 book ai didi

android - 写 Parcelable 对象得到 java.io.NotSerializableException

转载 作者:太空狗 更新时间:2023-10-29 12:47:04 29 4
gpt4 key购买 nike

我有一个名为 Shop 的类,它有 2 个字段和 1 个静态字段。该类实现了Parcelable接口(interface):

public class Shop implements Parcelable{
private static int SHOP_ID = 12;

private String name;
private long fund;

//constructor with parcel
public Shop(Parcel parcel){
name = parcel.readString();
fund = parcel.readLong();
}

//normal constructor
public Shop(Owner owner){
name = owner.getShopName();
fund = owner.getFund();
}

@Override
public int describeContents() {
return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeLong(fund);
}

public static final Creator<Shop> CREATOR = new Creator<Shop>(){

@Override
public Shop createFromParcel(Parcel parcel) {
//use the constructor which accept parcel
return new Shop(parcel);
}

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

};
}

现在,我的代码使用普通构造函数启动一个 Shop 实例:

Owner owner = getOwnerInfo();
Shop myShop = new Shop(owner); //initiate a Shop with owner

然后,我的代码将 shop 实例存储到 Android 的内部存储中:

String fileName = "shop_file";
try{
FileOutputStream fos = activity.openFileOutput(fileName,Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);

oos.writeObject(myShop);
oos.flush();
oos.close();
}catch(Exception ex){
...
}

但是当运行我的应用程序时,我得到了 java.io.NotSerializableException :

06-12 13:04:29.258: W/System.err(2632): java.io.NotSerializableException: com.my.app.model.Shop
06-12 13:04:29.258: W/System.err(2632): at java.io.ObjectOutputStream.writeNewObject(ObjectOutputStream.java:1364)
06-12 13:04:29.266: W/System.err(2632): at java.io.ObjectOutputStream.writeObjectInternal(ObjectOutputStream.java:1671)
06-12 13:04:29.266: W/System.err(2632): at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:1517)

为什么?我哪里错了?

最佳答案

从执行看来,您正在尝试序列化未实现 Serializable 的 CartData 实例:

java.io.NotSerializableException: com.my.app.model.Shop

如果你想序列化它,你应该让 Shop implemensts Serializable

来自doc

Parcel is not a general-purpose serialization mechanism. This class (and the corresponding Parcelable API for placing arbitrary objects into a Parcel) is designed as a high-performance IPC transport. As such, it is not appropriate to place any Parcel data in to persistent storage: changes in the underlying implementation of any of the data in the Parcel can render older data unreadable.

关于android - 写 Parcelable 对象得到 java.io.NotSerializableException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17063151/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com