无法将hashmap对象保存到android中的文件中

时间:2013-04-24 12:35:26

标签: android serialization hashmap lazy-loading drawable

我从互联网下载大量图片并存储到hashmap并显示在ListView中。我想缓存图像。为此,我将Hashmap对象存储到我的活动的onDestroy()内的文件中,并在oncreate()内取回对象。

Map<String, Drawable> hashmap; //storing the urls of images and downloaded image `Drawables` into this map 

内部onCreate()

       File f = new File(Environment.getExternalStorageDirectory()+"/image_cache.ser");
        if(f.exists()){ 
            FileInputStream fin = new FileInputStream(f);
            ObjectInputStream ois = new ObjectInputStream(fin);
            hashmap = (HashMap<String, Drawable>)ois.readObject();
            ois.close();
            Here creating a custom adapter and showing the hashmap drawable images in a listview 
          }

在onDestroy()

@Override
protected void onDestroy() {
    super.onDestroy();
    File f = new File(Environment.getExternalStorageDirectory()+"/image_cache.ser");

    try {
        if(hashmap != null && hashmap.size() >= 1){

            FileOutputStream fout = new FileOutputStream(f);
            ObjectOutputStream oos = new ObjectOutputStream(fout);
            oos.writeObject(hashmap);
            oos.flush();
            oos.close();

        }
    } catch (Exception e) {
        e.printStackTrace();
        f.delete();
    }

}

问题:获得此例外:

java.io.NotSerializableException android.graphics.drawable.BitmapDrawable inside ondestoy().

为什么hashmap object没有被序列化?我哪里错了。如果我错误地缓存图片,你能否以正确的方式对我说话?

2 个答案:

答案 0 :(得分:0)

您无法编写散列图,因为类Drawable不是Serializable

Drawable未实施Serializable

答案 1 :(得分:0)

它不会以这种方式工作。错误说,你正在尝试序列化一个未实现的Drawable,因为有工厂以不同的方式这样做。这个hashmap没有简单的解决方案。