0

I have an object with a BitmapDrawable field that I would like to serialize. I've implemented custom serialization/deserialization with the following methods:

private void writeObject(ObjectOutputStream out) throws IOException {
    out.defaultWriteObject();
    art.getBitmap().compress(Bitmap.CompressFormat.WEBP, 100, out);
}

private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    in.defaultReadObject();
    art = new BitmapDrawable(BitmapFactory.decodeStream(in));
}

This works, except that the BitmapDrawable constructor without resources is deprecated, and I'd like to use the preferred constructor. What is a good way to get an Android context passed down into readObject?

Nick
  • 6,900
  • 5
  • 45
  • 66
  • Does your object class use a `Context` for anything else? Do you pass it one in its constructor? – Mike M. Nov 09 '15 at 03:35
  • No, but if I did pass it one just for this, because I need it in the readObject method, I assume I wouldn't want to be serializing contexts, so in readObject I wouldn't have access to it, right? – Nick Nov 09 '15 at 03:38
  • 1
    Right, right. You can't serialize `Context`s, even if you wanted to. You may have to alter your class to hold just the `Bitmap`, and create a `BitmapDrawable` as needed. Otherwise, you might just be stuck with the deprecated constructor. – Mike M. Nov 09 '15 at 03:41
  • Well, the problem with using the deprecated constructor is that by not having the resources means that the density gets set incorrectly – Nick Nov 09 '15 at 03:43
  • 1
    Yeah, I'd've gone with my first suggestion, anyway. Seems cleaner. Then you could just implement a factory method that takes a `Context` and returns a `BitmapDrawable`. – Mike M. Nov 09 '15 at 03:47
  • 1
    That seems reasonable, and did the trick. Thanks for the suggestion! – Nick Nov 09 '15 at 03:55

1 Answers1

0

Going to quote Mike M's answer from the comments above so that this question can be closed.

You may have to alter your class to hold just the Bitmap, and create a BitmapDrawable as needed.

Basically instead of turning the Bitmap into a BitmapDrawable in the class, I do it in the activities where I need a Drawable (because I have access to a context in those locations). So instead of serializing a BitmapDrawable I am serializing a Bitmap, which does not require a context to deserialize.

Nick
  • 6,900
  • 5
  • 45
  • 66