【问题标题】:Unable to save a hashmap object into a file in android无法将哈希图对象保存到android中的文件中
【发布时间】:2013-04-24 12:35:25
【问题描述】:

我正在从 Internet 下载大量图像并将其存储到 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 没有被序列化?我哪里出错了。如果我缓存图像有误,请您以正确的方式告诉我?

【问题讨论】:

  • java.io.NotSerializableException .... java.io.NotSerializableException .... java.io.NotSerializableException

标签: android serialization hashmap lazy-loading drawable


【解决方案1】:

你不能写你的hashmap,因为Drawable这个类不是Serializable

Drawable 没有实现Serializable

【讨论】:

    【解决方案2】:

    这种方式是行不通的。错误表明,您正在尝试序列化未实现的 Drawable,因为有工厂以不同的方式这样做。这个 hashmap 没有简单的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-07
      • 2020-10-28
      • 1970-01-01
      • 2013-07-10
      • 2012-03-27
      相关资源
      最近更新 更多