mirugai
mirugai

Reputation: 175

Caching bitmaps - Android

I have a ListView where each cell contains a bitmap that is downloaded from the internet. To avoid out of memory errors I was wondering what the best way is to deal with this.

I have looked at softreferences for the bitmaps but I was wondering what happens if I am in the current activity and the the application begins to run out of memory. How does it decide what bitmaps to recycle?

Is a better way to write the file to disk and load it into memory when I need it? Are there any examples?

Thanks

Upvotes: 2

Views: 2900

Answers (2)

Yahel
Yahel

Reputation: 8550

There is a lot of implementation of a list view with lazy loading of images with reuse of the views via the convertView mecanism. For example, take a look here : Lazy load of images in ListView

There are quite a few solutions there.

Upvotes: 1

Knickedi
Knickedi

Reputation: 8787

I dealt with that a while ago. Experimented with performance too. Here's what I got.
This answer is beyond lazy loading of images because it deals with performance.

First of all: Forget about SoftReferences on android. Very bad for caching because of misbehavior (released to soon). I ended up using LruCache (source for API < 12) with a fixed byte size for the cache.

When loading images through network you want to persist the loaded images (in private app data folder or SD card). Otherwise the user is forced to load (unnecessary) data on every app startup. Here's the routine:

  1. image is requested
  2. check for image in memory cache (jump to 6. if available)
  3. is persisted locally (jump to 5. if so)
  4. load from network and persist
  5. load bitmap into cache
  6. load bitmap from cache into view

Now some words for performance. If every list item has another image and they have a fixed size (e.g. 40 x 40 dip) you would waste cache memory when loading full images (e.g. 800 x 600 px) and your device would have to calculate a lot for scaling.

First solution is to prescale the bitmap on step 5. before loading image into cache. You'll get the best performance when you persist the scaled image and load it next time.

You can find an example in my CoverCache helper (CD covers - but can be used for any kind of image data). It deals with persisting, scaling and caching images at the same time.

Upvotes: 8

Related Questions