Android可序列化问题

标签 android bitmap serializable

我创建了一个类,它有几个成员变量,所有成员变量都是可序列化的……除了一个Bitmap!我尝试扩展位图并实现可序列化,不认为位图是最终类。

我想保存类(它基本上构成了游戏的当前状态)以便玩家可以选择并加载游戏。

在我看来,我有两个选择: 1)寻找另一种保存游戏状态的方法。如有任何帮助,我们将不胜感激。

2) 将位图成员变量更改为 int,例如,并创建一个 BitmapGetter 类,该类具有基于 int 返回位图的静态方法。 (这个选项并不容易,因为我的类(class)包含如此多的位图可能性,而我创建游戏的方式意味着这将需要付出难以置信的努力。

基本上,除了我自己懒惰地创建一个位图变量而不考虑任何人之外,我没有人可以责怪,但我将不胜感激任何帮助...

最佳答案

如何用这样的类替换位图:

public class SerialBitmap implements Serializable {

    public Bitmap bitmap;

    // TODO: Finish this constructor
    SerialBitmap(<some params>) {
        // Take your existing call to BitmapFactory and put it here
        bitmap = BitmapFactory.decodeSomething(<some params>);
    }

    // Converts the Bitmap into a byte array for serialization
    private void writeObject(java.io.ObjectOutputStream out) throws IOException {
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 0, byteStream);
        byte bitmapBytes[] = byteStream.toByteArray();
        out.write(bitmapBytes, 0, bitmapBytes.length);
    }

    // Deserializes a byte array representing the Bitmap and decodes it
    private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        int b;
        while((b = in.read()) != -1)
            byteStream.write(b);
        byte bitmapBytes[] = byteStream.toByteArray();
        bitmap = BitmapFactory.decodeByteArray(bitmapBytes, 0, bitmapBytes.length);
    }
}

重写的 Serializable.writeObject() 和 readObject() 方法序列化字节而不是位图,因此该类是可序列化的。您将需要完成构造函数,因为我不知道您当前是如何构建位图的。最后要做的是用 YourClass.serialBitmap.bitmap 替换对 YourClass.bitmap 的引用。

祝你好运!

巴里 附言这段代码可以编译,但我还没有用真实的位图对其进行测试

关于Android可序列化问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6002800/

相关文章:

java - 字符串填充后变空

android - Google Play 上传失败,因为 google play 服务版本问题

android - 无法从共享首选项中保存的 URI 加载图像

c# - 如何序列化 CustomLineCap 类的实例

.net - 如何在 .net 中使没有 Serializable 属性的类可序列化

java - 什么时候 Java 对象可序列化但不可克隆才有意义?

java - 如何在 android studio 的弹出窗口中添加带滚动的 listView?

android - FTS3 中的多列匹配

java - 将随机图像设置为imageview android

android - 通过我的应用程序捕获图像后如何调整位图大小