我已經通過以下鏈接安卓:從服務器上下載圖像,並將它們保存在設備緩存
和我按照下面的教程做加載它之後緩存圖像消失從服務器
和我的代碼段:
private Bitmap getBitmap(String url) {
// PhotoToLoad photoToLoad = new PhotoToLoad(url, new ImageView(a));
// String filename = photoToLoad.url;
//String filename = url;
String filename = String.valueOf(url.hashCode());
Log.v("TAG FILE :", filename);
File f = new File(cacheDir, filename);
// Is the bitmap in our cache?
Bitmap bitmap = BitmapFactory.decodeFile(f.getPath());
if (bitmap != null)
return bitmap;
else {
// Nope, have to download it
try {
bitmap = BitmapFactory.decodeStream(new URL(url)
.openConnection().getInputStream());
// save bitmap to cache for later
writeFile(bitmap, f);
return bitmap;
} catch (FileNotFoundException ex) {
ex.printStackTrace();
Log.v("FILE NOT FOUND", "FILE NOT FOUND");
return null;
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return null;
}
}
}
private void writeFile(Bitmap bmp, File f) {
FileOutputStream out = null;
try {
out = new FileOutputStream(f);
bmp.compress(Bitmap.CompressFormat.PNG, 80, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null)
out.close();
} catch (Exception ex) {
}
}
}
我得到FileNotFoundException
:
11-12 15:19:25.495: VERBOSE/cacheDir(266): /sdcard/data/BalajeeBazaar
11-12 15:19:26.035: VERBOSE/TAG FILE :(266): -951166081
11-12 15:19:26.315: WARN/System.err(266): java.io.FileNotFoundException: /sdcard/data/BalajeeBazaar/-951166081
11-12 15:19:26.315: WARN/System.err(266): at org.apache.harmony.luni.platform.OSFileSystem.open(OSFileSystem.java:231)
11-12 15:19:26.315: WARN/System.err(266): at java.io.FileOutputStream.<init>(FileOutputStream.java:96)
11-12 15:19:26.315: WARN/System.err(266): at java.io.FileOutputStream.<init>(FileOutputStream.java:69)
11-12 15:19:26.315: WARN/System.err(266): at com.ecommerce.balajeebazaar.CacheImages.writeFile(CacheImages.java:160)
11-12 15:19:26.315: WARN/System.err(266): at com.ecommerce.balajeebazaar.CacheImages.getBitmap(CacheImages.java:142)
11-12 15:19:26.315: WARN/System.err(266): at com.ecommerce.balajeebazaar.CacheImages.access$0(CacheImages.java:125)
11-12 15:19:26.315: WARN/System.err(266): at com.ecommerce.balajeebazaar.CacheImages$PhotosLoader.run(CacheImages.java:77)
11-12 15:19:26.325: WARN/dalvikvm(266): threadid=17: thread exiting with uncaught exception (group=0x4001aa28)
11-12 15:19:26.325: ERROR/AndroidRuntime(266): Uncaught handler: thread Thread-10 exiting due to uncaught exception
11-12 15:19:26.325: ERROR/AndroidRuntime(266): java.lang.ClassCastException: android.graphics.Bitmap
11-12 15:19:26.325: ERROR/AndroidRuntime(266): at com.ecommerce.balajeebazaar.CacheImages$PhotosLoader.run(CacheImages.java:79)
請指導我如何解決這個問題?
謝謝〜
您是否已將您添加到清單中: ?嘗試這個項目在這裏工作對我來說:https://github.com/thest1/LazyList –
是的,我已經加入它 – Shruti