我有一个名为Shop的类,它具有2个字段和1个静态字段.该类实现Parcelable接口:
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.Shop06-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全部内容,希望文章能够帮你解决android-编写Parcelable对象获取java.io.NotSerializableException所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)