Problem serializing Drawable
Asked Answered
C

2

2

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.

Caressive answered 2/2, 2011 at 22:21 Comment(0)
T
2
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

Tahr answered 2/2, 2011 at 23:1 Comment(1)
Thanks for the answer! That's the solution I was looking for.Caressive
L
2

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.

Loggia answered 2/2, 2011 at 23:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.