【问题标题】:can't add items to lrucache无法将项目添加到 lrucache
【发布时间】: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 中没有放入任何内容

标签: android android-lru-cache


【解决方案1】:

我遇到了同样的问题。确保您分配的缓存大小足以接受一个元素。如果你尝试插入一个太大的元素,LruCache 不会报错,它会静默失败。

【讨论】:

    猜你喜欢
    • 2013-06-14
    • 1970-01-01
    • 1970-01-01
    • 2015-10-20
    • 2021-01-26
    • 2018-04-28
    • 2011-10-30
    • 2021-07-01
    • 2019-06-21
    相关资源
    最近更新 更多