【发布时间】:2014-10-30 20:59:29
【问题描述】:
我正在尝试使用 LRUcache 来缓存我的应用从 Web 下载的一些图像。我已经阅读了来自 android 开发人员的教程,但我无法在我的 LRUcache 中添加任何内容。 这是我的代码,
class myloader extends Activity{ String url;ImageView imview;Bitmap map;LruCache<String, Bitmap> myCache=new LruCache<String, Bitmap> (5*1024*1024)
class load extends AsyncTask<String, Void, Bitmap>{
WeakReference <ImageView> ref=new WeakReference<ImageView>(imview);
String url2;
public load(ImageView imageView) {
ref = new WeakReference<ImageView>(imageView);
}
@Override
protected Bitmap doInBackground(String... params) {
try {
u=new URL(params[0]);
map=BitmapFactory.decodeStream(u.openConnection().getInputStream(),null,listDimensions());
myCache.put(url,map);
} catch (MalformedURLException e) {e.printStackTrace();
} catch (IOException e) {e.printStackTrace();}
return map;
}
@Override
protected void onPostExecute(Bitmap result) {
if (ref != null) {
ImageView imageView = ref.get();
toLoad bitmapDownloaderTask = getBitmapDownloaderTask(imageView);
if (this == bitmapDownloaderTask) {
imageView.setImageBitmap(result);
}
}
} public void download(String theurl,ImageView im) { url=theurl; // here i check for lrucache items
imview=im;
if (cancelPotentialDownload(url, imview)) {
toLoad task = new toLoad(imview);
DownloadedDrawable downloadedDrawable = new DownloadedDrawable(task);
Bitmap finalBit=myCache.get(url);
if (finalBit!=null){
imview.setImageBitmap(finalBit);
}else{
imview.setImageDrawable(downloadedDrawable);
task.execute(url);
}
t=myCache.putCount();
}
}
然后从我的适配器类的 getview() 调用 myloader,传递一个 imageview 和一个图像 url
【问题讨论】:
-
添加更多信息。
cache开了吗?你得到什么例外? -
你说的打开是什么意思?我没有得到任何异常。当我后来尝试获取这些位图并显示它们时,我不能。我也使用了 size() 方法并得到了零条目。所以我得出结论,我的缓存中没有添加任何内容。
-
您不能在
extend Activity的类中使用构造函数。 Activity 由 Android 框架创建,框架不会调用您的构造函数。 -
不知道!!我删除了构造函数。现在我在我的适配器类上创建了一个 myloader 类的对象,然后我调用了下载(String s,ImageView i, LRUcache
l) 方法。但问题依然存在 -
当我在 download() 中调用 putCount() 方法时,它返回 0,所以在 doinbackground 的 lrucache 中没有放入任何内容