我正在尝试保存对象列表的状态。对象类中的一个字段是位图。由于Bitmap不可序列化,因此我实现了自己的实现Serializable的位图类。我已经看过其他问题来创建这个类,它似乎应该工作。但是当我运行应用程序时,它在我的serializableBitmap类中执行writeObject方法后立即崩溃。但是当它崩溃时,并没有说它不幸地停止工作,但它只是简单地回到主屏幕。它也不会在LogCat中输出任何错误消息。所以我不知道导致崩溃的原因。这是我的serializableBitmap类:
public class serializableBitmap implements Serializable {
private static final long serialVersionUID = -5228835919664263905L;
private Bitmap bitmap;
public serializableBitmap(Bitmap b) {
bitmap = b;
}
// Converts the Bitmap into a byte array for serialization
private void writeObject(ObjectOutputStream out) throws IOException {
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
boolean success = bitmap.compress(Bitmap.CompressFormat.PNG, 0, byteStream);
byte bitmapBytes[] = byteStream.toByteArray();
if (success)
out.write(bitmapBytes, 0, bitmapBytes.length);
}
// Deserializes a byte array representing the Bitmap and decodes it
private void readObject(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);
}
public Bitmap getBitmap() {
return this.bitmap;
}
}
任何帮助都会非常感激。
哦,在我的对象类中包含我实现Parcelable的位图,然后在writeToParcel方法中我调用
dest.writeList(bitmaps);
位图是
private ArrayList<serializableBitmap> bitmaps;
答案 0 :(得分:1)
我对更大的位图有同样的问题。较小的位图(约500 x 300px)工作正常。
尽量避免序列化大型位图并将其加载到需要的位置。例如,您可以序列化其URL并在以后加载它们或将它们写入本地存储。