otSerializableException而写序列化对象到外

otSerializableException而写序列化对象到外

本文介绍了java.io.NotSerializableException而写序列化对象到外部存储?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

朋友,

我用下面的code写的序列化对象到外部存储器。

i am using following code to write Serializable object to external storage.

这引发了我的错误java.io.NotSerializableException甚至我的对象是可序列化的任何一个指导我什么错误,我在干嘛?

it throws me error java.io.NotSerializableExceptioneven my object is serializable any one guide me what mistake am i doing?

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);

任何帮助将是AP preciated。

any help would be appreciated.

推荐答案

这失败,因为在你的类中的上下文字段。上下文对象不能序列化。

This fails due to the Context field in your class. Context objects are not serializable.

按照序列化文档 - 当遍历图中,一个对象可能会遇到不支持Serializable接口。在这种情况下NotSerializableException将被抛出并且将识别的类的非序列化的对象的

Per the Serializable documentation - "When traversing a graph, an object may be encountered that does not support the Serializable interface. In this case the NotSerializableException will be thrown and will identify the class of the non-serializable object."

您可以删除上下文场全部或瞬态特性应用到上下文字段,以便它不是序列。

You can either remove the Context field entirely, or apply the transient attribute to the Context field so that it is not serialized.

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

这篇关于java.io.NotSerializableException而写序列化对象到外部存储?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 19:58