【问题标题】:java.io.NotSerializableException while writing Serializable object to external storage?java.io.NotSerializableException 将 Serializable 对象写入外部存储?
【发布时间】:2011-05-31 22:00:30
【问题描述】:

朋友们,

我正在使用以下代码将 Serializable 对象写入外部存储。

它抛出错误 java.io.NotSerializableException 甚至我的对象是可序列化的任何人都指导我我在做什么错误?

public class MyClass implements Serializable 
{

// other veriable stuff here...
    public String title;
    public String startTime;
    public String endTime;
    public boolean classEnabled;
    public Context myContext;

 public MyClass(Context context,String title, String startTime, boolean enable){
            this.title = title;
            this.startTime = startTime;
            this.classEnabled = enable;
            this.myContext = context;

}

 public boolean saveObject(MyClass obj) {

        final File suspend_f=new File(cacheDir, "test");

            FileOutputStream   fos  = null;
            ObjectOutputStream oos  = null;
            boolean            keep = true;

            try {
                fos = new FileOutputStream(suspend_f);
                oos = new ObjectOutputStream(fos);
                oos.writeObject(obj);   // exception throws here
            }
            catch (Exception e) {
                keep = false;


            }
            finally {
                try {
                    if (oos != null)   oos.close();
                    if (fos != null)   fos.close();
                    if (keep == false) suspend_f.delete();
                }
                catch (Exception e) { /* do nothing */ }
            }


            return keep;


        }

}

并从活动类调用以保存它

 MyClass m= new MyClass(this, "hello", "abc", true);
 boolean  result =m.saveObject(m);

任何帮助将不胜感激。

【问题讨论】:

    标签: android serialization


    【解决方案1】:

    由于您班级中的 Context 字段,此操作失败。上下文对象不可序列化。

    根据Serializable documentation - “在遍历图形时,可能会遇到不支持可序列化接口的对象。在这种情况下,将抛出 NotSerializableException 并将识别不可序列化对象的类。”

    您可以完全删除 Context 字段,也可以将瞬态属性应用于 Context 字段,使其不被序列化。

    public class MyClass implements Serializable 
    {
        ...
        public transient Context myContext;
        ...
    }
    

    【讨论】:

    • 那有什么解决办法呢?有什么想法吗?
    • 关于您的评论的更新答案
    • 你不能简单地为上下文字段设置“瞬态”吗?
    • @androiddeveloper 好点!这是一个更好的解决方案,我相应地更新了答案。
    • 太糟糕了,我没有自己写答案... :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多