2011-07-14 37 views
5

我試圖通過緩存圖像並在滾動列表時加載它們從手機而不是互聯網加速我的ListView。但是,當我試圖序列化Drawable對象時,我遇到了異常。這是我的函數:序列化Android上的Drawable對象

java.io.NotSerializableException:

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

的代碼導致這個漂亮位android.graphics.drawable.BitmapDrawable

什麼是序列化的最佳方法這些圖像?

回答

6

您應該只需要緩存的位圖(可繪)存儲它們,你也就是從互聯網上獲取。其他所有可繪製對象很可能在您的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(); 
    } 
} 
+0

這似乎工作,但我將如何去讀取存儲的圖像回到我的應用程序? – karl

-2

請參閱http://code.google.com/p/shelves/谷歌Shleves項目中,他們實際上是做你想要什麼。請查看他們正在維護WeakReference和SoftReference到圖像的代碼。

+0

svn結帳http://shelves.googlecode.com/svn/trunk/ –