Friday, August 13, 2010

Save image in instance state (Android)

While working on an app, I had an activity that downloaded an image from the Internet and displayed it to the user (amongst other things). Because all of the data presented to the user is downloaded from the Internet, it's mandatory for me to save this data in onSaveInstanceState() and restore it in onCreate().

At first, I had a problem. I was downloading the image to a Drawable, using Drawable.createFromStream(). Now, because a Drawable is dependent on its Context, it can't be serialized or parceled.

The solution was to use a Bitmap instead, which thankfully implements Parcelable. Downloading a Bitmap is easy:

URL url = new URL("http://www.example.com/pic.jpg"); Bitmap bitmap = BitmapFactory.decodeStream(url.openStream());

Then saving it in the instance state is even easier:

public void onSaveInstanceState(Bundle outState) { outState.putParcelable("bitmap", bitmap); }

Restoring:

if (savedInstanceState != null) bitmap = (Bitmap) savedInstanceState.getParcelable("bitmap");

And there you have it, simple as pie.