2013-04-24 49 views
-1

我正在從互聯網下載大量圖像並將其存儲到hashmap中,並在ListView中顯示。我想緩存圖像。爲此,我將Hashmap對象存儲到我的活動的onDestroy()內的文件中,並取回oncreate()中的對象。無法將哈希表對象保存到Android中的文件

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().

爲什麼hashmapobject沒有被序列化?我去哪裏錯了。如果我錯誤地緩存圖像,能否請您以正確的方式進行處理?

+0

java.io.NotSerializableException .... java.io.NotSerializableException .... java.io.NotSerializableException – Selvin 2013-04-24 12:38:25

回答

0

,因爲該類Drawable是不是你不能寫你的HashMap Serializable

Drawable沒有實現Serializable

0

它只是不會以這種方式工作。錯誤說,你正試圖序列化一個Drawable,這是沒有實現的,因爲有工廠以不同的方式這樣做。這個hashmap沒有簡單的解決方案。