Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing a Drawable object on Android

I'm trying to speed up my ListView by cacheing the images and loading them from the phone rather than the internet when scrolling the list. However, I run into an exception when I try to serialize the Drawable object. This is my function:

    private void cacheImage(Drawable dr, Article a){
    FileOutputStream fos;
    try {
        fos = openFileOutput(a.getArticleId().toString(), Context.MODE_PRIVATE);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(dr); 
        oos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }catch(IOException e){
        e.printStackTrace();
    }
}

This nifty bit of code results in:

java.io.NotSerializableException: android.graphics.drawable.BitmapDrawable

What is the best approach to serialize these images?

like image 393
karl Avatar asked Jul 14 '11 11:07

karl


People also ask

How to make userinfo serializable object in Android?

This object data we are passing between MainActivity and SecondActivity. To make Userinfo serializable object we should implement the java.io.Serializable interface as shown below − Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer.

What is the use of drawable in Android?

Drawables overview. When you need to display static images in your app, you can use the Drawable class and its subclasses to draw shapes and images. A Drawable is a general abstraction for something that can be drawn.

How does serialization work with intent in Android?

Before getting into the code, we should know about serialization and how does it work with intent in android. Serialization is a marker interface. Using serialization, we can convert state of an object into a byte stream. The byte stream is a platform independent, so it's going to work on the JVM and other platforms.

How to set the level value of the drawable in Android?

Setting the level value of the drawable with setLevel () loads the drawable resource in the level list that has a android:maxLevel value greater than or equal to the value passed to the method. The filename is used as the resource ID.


1 Answers

You should only need to cache bitmap (drawables) that you i.e. fetched from the internet. All other drawables are most likely in your apk.

If you want to write a Bitmap to file you can use the Bitmap class:

private void cacheImage(BitmapDrawable dr, Article a){
    FileOutputStream fos;
    try {
        fos = openFileOutput(a.getArticleId().toString(), Context.MODE_PRIVATE);
        dr.getBitmap().compress(Bitmap.CompressFormat.PNG, fos);
        fos.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }catch(IOException e){
        e.printStackTrace();
    }
}
like image 63
thaussma Avatar answered Oct 13 '22 15:10

thaussma