1

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 と image url を渡します

4

1 に答える 1

0

私も同じ問題を抱えていました。割り当てたキャッシュ サイズが、1 つの要素を受け入れるのに十分な大きさであることを確認してください。大きすぎる要素を挿入しようとしても、LruCache は文句を言わず、黙って失敗します。

于 2014-10-30T12:59:29.383 に答える