我有一个有三个字段的单个对象:两个字符串和一个Drawable
public class MyObject implements Serializable {
private static final long serialVersionUID = 1L;
public String name;
public String lastName;
public Drawable photo;
public MyObject() {
}
public MyObject(String name, String lastName, Drawable photo) {
this.name = name;
this.lastName = lastName;
this.photo = photo;
}
}
我要做的是将ArrayList
这些对象保存到文件中,但我不断获得NotSerializableException
02-02 23:06:10.825: WARN/System.err(13891): java.io.NotSerializableException: android.graphics.drawable.BitmapDrawable
我用来存储文件的代码:
public static void saveArrayList(ArrayList<MyObject> arrayList, Context context) {
final File file = new File(context.getCacheDir(), FILE_NAME);
FileOutputStream outputStream = null;
ObjectOutputStream objectOutputStream = null;
try {
outputStream = new FileOutputStream(file);
objectOutputStream = new ObjectOutputStream(outputStream);
objectOutputStream.writeObject(arrayList);
}
catch(Exception e) {
e.printStackTrace();
}
finally {
try {
if(objectOutputStream != null) {
objectOutputStream.close();
}
if(outputStream != null) {
outputStream.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
当drawable未初始化时,一切正常。 提前感谢您的帮助。
答案 0 :(得分:2)
java.io.NotSerializableException: android.graphics.drawable.BitmapDrawable
此消息似乎非常清楚 - photo
字段中的特定可绘制实例是BitmapDrawable,其设计不是为了序列化。如果不处理非序列化字段,则无法序列化您的类。
如果您可以确保您的课程始终有BitmapDrawable
或Bitmap,则可以查看此代码,了解如何处理Bitmap
字段的示例:
答案 1 :(得分:2)
您无法序列化。
简单地说,如果BitmapDrawable不是Serializable,那么你就无法序列化它。通常这样的事情是不可序列化的,因为它们坚持引用非纯数据的东西。像绘图表面的上下文或句柄。