java 存入对象io,java.io.NotSerializableException而写序列化对象到外部存储?

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.

解决方案

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;

...

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值