【问题标题】:Problem serializing Drawable序列化Drawable的问题
【发布时间】:2011-06-20 07:36:21
【问题描述】:

我有一个包含三个字段的单一对象:两个字符串和一个 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();
        }
    }
}

当可绘制对象未初始化时,一切正常。 提前感谢您的帮助。

【问题讨论】:

    标签: java android drawable serializable


    【解决方案1】:
    java.io.NotSerializableException: android.graphics.drawable.BitmapDrawable
    

    这条消息看起来很清楚 - photo 字段中的特定可绘制实例是 BitmapDrawable,它不是为序列化而设计的。如果不处理不可序列化的字段,您的类就无法序列化。

    如果您可以确保您的课程始终有 BitmapDrawableBitmap,您可以查看此代码以获取有关如何处理 Bitmap 字段的示例:

    android how to save a bitmap - buggy code

    【讨论】:

    • 感谢您的回答!这就是我一直在寻找的解决方案。
    【解决方案2】:

    你不能序列化它。

    简单地说,如果 BitmapDrawable 不是 Serializable,那么你就不能序列化它。通常像这样的东西是不可序列化的,因为它们持有对非纯数据的东西的引用。类似于上下文或绘图表面的句柄。

    【讨论】:

      猜你喜欢
      • 2010-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多