gpt4 book ai didi

android - 将 Serializable 对象写入外部存储时出现 java.io.NotSerializableException?

转载 作者:可可西里 更新时间:2023-11-01 19:08:48 26 4
gpt4 key购买 nike

friend ,

我正在使用以下代码将可序列化对象写入外部存储。

它抛出错误 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;


}

}

并从 Activity 类中调用以保存它

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

如有任何帮助,我们将不胜感激。

最佳答案

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

根据 Serializable documentation - "当遍历一个图时,可能会遇到不支持Serializable接口(interface)的对象。在这种情况下,将抛出NotSerializableException异常,并识别不可序列化对象的类。"

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

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

关于android - 将 Serializable 对象写入外部存储时出现 java.io.NotSerializableException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4551926/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com