Serializing a Drawable object on Android

放肆的年华 提交于 2019-12-08 19:47:55

问题


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?


回答1:


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();
    }
}



回答2:


In case your Drawables are all Bitmaps you can store them using Bitmap.compress()




回答3:


Please see http://code.google.com/p/shelves/ Google Shleves project they are actually doing what you want. please see code they are maintaining WeakReference and SoftReference to Images.



来源:https://stackoverflow.com/questions/6692492/serializing-a-drawable-object-on-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!