在安卓上序列化一个可绘制对象

6

我正在尝试通过缓存图片并在滚动列表时从手机加载图片而不是从互联网加载来加速我的ListView。然而,当我尝试序列化Drawable对象时遇到了异常。这是我的函数:

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

这段聪明的代码会导致以下错误:java.io.NotSerializableException: android.graphics.drawable.BitmapDrawable。针对这些图片,最好的序列化方法是什么?
3个回答

6

你只需要缓存从互联网获取的位图(drawable)。所有其他的drawable很可能已经在你的apk中了。

如果你想将位图写入文件,可以使用Bitmap类:

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

这似乎可行,但我该如何将存储的图像读取回我的应用程序中? - karl

0

如果你的Drawables都是Bitmaps,你可以使用Bitmap.compress()来存储它们。


-2
请查看http://code.google.com/p/shelves/ Google Shleves项目,他们正在做你想要的事情。请查看代码,他们正在维护对图像的弱引用和软引用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接