Reputation: 1548
I've got a singe object which has three fields: two strings and a 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;
}
}
What I'm trying to do, is to save an ArrayList
of these objects to a file, but i keep getting a NotSerializableException
02-02 23:06:10.825: WARN/System.err(13891): java.io.NotSerializableException: android.graphics.drawable.BitmapDrawable
The code which I use to store the file:
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();
}
}
}
Everything works fine when the drawable isn't initialized. Thanks in advance for any help.
Upvotes: 2
Views: 6594
Reputation: 8204
You can't serialize that.
Simply put, if BitmapDrawable isn't Serializable, then you can't serialize it. Usually things like this aren't serializable because they are holding on to references to things that aren't pure data. Like a context or a handle to a drawing surface.
Upvotes: 2
Reputation: 87573
java.io.NotSerializableException: android.graphics.drawable.BitmapDrawable
This message seems pretty clear - the specific drawable instance in the photo
field is a BitmapDrawable, which wasn't designed to be serialized. Your class cannot be serialized without dealing with the non-serializable field.
If you can ensure your class will always have a BitmapDrawable
or a Bitmap, you can see this code for an example of how to handle a Bitmap
field:
android how to save a bitmap - buggy code
Upvotes: 2