问题序列化Drawable [英] Problem serializing Drawable

查看:742
本文介绍了问题序列化Drawable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有三个字段的单个对象:两个字符串和一个 Drawable

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;
    }
}

我正在尝试做的是保存一个 ArrayList 这些对象到一个文件,但我一直得到 NotSerializableException

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.

推荐答案

java.io.NotSerializableException: android.graphics.drawable.BitmapDrawable

此消息似乎很清楚 - <中的特定可绘制实例code>照片字段是 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.

如果您可以确保您的类始终具有 BitmapDrawable 位图,您可以看到此代码如何处理位图字段的示例:

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如何保存位图 - 有缺陷的代码

这篇关于问题序列化Drawable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆