Android 将可序列化对象写入外部存储时发生java.io.NotSerializableException?
朋友们 我使用以下代码将可序列化对象写入外部存储器 它向我抛出错误java.io.NotSerializableException 即使我的对象是可序列化的任何人都可以指导我我犯了什么错误Android 将可序列化对象写入外部存储时发生java.io.NotSerializableException?,android,serialization,Android,Serialization,朋友们 我使用以下代码将可序列化对象写入外部存储器 它向我抛出错误java.io.NotSerializableException 即使我的对象是可序列化的任何人都可以指导我我犯了什么错误 public class MyClass implements Serializable { // other veriable stuff here... public String title; public String startTime; public String en
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);
任何帮助都将不胜感激。由于类中的上下文字段,此操作失败。上下文对象不可序列化 根据-“在遍历图形时,可能会遇到不支持Serializable接口的对象。在这种情况下,将引发NotSerializableException并标识不可序列化对象的类。” 您可以完全删除上下文字段,也可以将transient属性应用于上下文字段,使其不被序列化
public class MyClass implements Serializable
{
...
public transient Context myContext;
...
}
那么解决办法是什么呢?有什么想法吗?关于你的评论,更新了答案。你不能简单地为上下文字段设置“transient”吗?@androiddeveloper很好!这是一个更好的解决方案,我相应地更新了答案。可惜我当时没有写自己的答案…:)