0

quick question i have multiple bitmaps loading on a page to save time i save them to memory catch for sometime after its been loaded in however it should delete automatically once its full

but if i keep reloading the page eventually it will crash due to out of memory exception, i would like to clear all of the bitmaps including the ones in the catch once i reload the page because i am not sure when i am finished with each bitmap i have 5 imageViews that constantly change images simultaneously so its a bit difficult to keep track of them is there a way to do this?

    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    final int cacheSize = maxMemory / 8;

    mMemoryCache = new LruCache<String, Bitmap>(cacheSize) {
        @Override
        protected int sizeOf(String key, Bitmap bitmap) {
            // The cache size will be measured in kilobytes rather than
            // number of items.
            return bitmap.getByteCount() / 1024;
        }
    };

}

public void addBitmapToMemoryCache(String key, Bitmap bitmap) {
    if(getBitmapFromMemCache(key) == null) {
        mMemoryCache.put(key, bitmap);
    }
}

public Bitmap getBitmapFromMemCache(String key) {
    return mMemoryCache.get(key);
}

public void loadBitmap(String resId, ImageView imageView) {
    final String imageKey = String.valueOf(resId);
    iv = imageView.getWidth();
    Bitmap bitmap = getBitmapFromMemCache(imageKey);
    if(bitmap != null) {
        imageView.setImageBitmap(bitmap);
    }else{
        if(cancelPotentialWork(imageKey, imageView)){
            Bitmap loading = decodeSampledBitmapFromResource(ctx.getResources(), R.drawable.whiteseetrough, imageView.getWidth(), imageView.getWidth());
            BitmapWorkerTask task = new BitmapWorkerTask(imageView);
            AsyncDrawable asyncDrawable = new AsyncDrawable(ctx.getResources(), loading, task);
            imageView.setImageDrawable(asyncDrawable);
            task.execute(resId);
        }
    }
}

here is my code to load the bitmap and add to catch i call it using

bitmapHTTP getBitmap = new bitmapHTTP(this);

getBitmap.loadBitmap(picUrl, imageView);
user2692997
  • 2,001
  • 2
  • 14
  • 20

2 Answers2

0

call this method of LruCache in your refreshing method

mMemoryCache.evictAll()
masoud vali
  • 1,528
  • 2
  • 18
  • 29
0

First, you need to call bitmap.recycle() after finishing using it, just freeing references is not enough.

Note the set in cache and set in use are not always the same (though in particular cases they can be same, depending on your usage). If they can diverge, you have to keep track of used images in separate data structure, for example by maintaining reference count and overriding LRUCache methods to track and recycle when appropriate.

This is not that simple, see When should I recycle a bitmap using LRUCache? for discussion and code.

Community
  • 1
  • 1
Fedor Losev
  • 3,244
  • 15
  • 13