Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

android - java.io.NotSerializableException while writing Serializable object to external storage?

friends,

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

it throws me error java.io.NotSerializableException even 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;


        }

}

and calling from activity class to save it

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

any help would be appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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;
    ...
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...