2

I am writing an android app which will have an image feed, something like in for example the instagram app. My question is how can I cache these images so i dont get an out of memory exception?

I have read some tutorials, but all of them are caching Bitmaps in LruCache. I might be wrong but as I think the bitmap in the ImageView and a cached one use the same ammount of memory.

I'm thinking about storing the compressed images (for example JPEG) in an in-memory cache (and of course on the disk) and showing it only when it is visible on the screen, but then the CPU will eat up the battery as it will constantly clearing the ImageView when it's not visible and decompressing the image and showing it when it is in the viewport. And I'm not really sure that the scrolling will be lagless, even if I do it on a new thread.

An alternative is to do the same as I described above, but I wont remove the bitmap from the imageview immediately, only when there are a lot of images and i will run out of memory.

What do you think?

vsakos
  • 492
  • 8
  • 19
  • possible duplicate of [Android image caching](http://stackoverflow.com/questions/1945201/android-image-caching) – RNK Jan 26 '15 at 17:41

1 Answers1

2

Here is an example step-by-step on how to cache images, in memory and disk:

http://androidexample.com/Download_Images_From_Web_And_Lazy_Load_In_ListView_-_Android_Example/index.php?view=article_discription&aid=112&aaid=134

But you can also use libs that already work pretty well like :

http://square.github.io/picasso/

The first link also contains explanation on how you should treat bitmaps to avoid outOfMemory.

vinitius
  • 3,212
  • 2
  • 17
  • 22
  • but both of these are caching bitmaps with a file cache callback. isn't there any other method? – vsakos Jan 26 '15 at 20:25
  • loading from the disk is slow, i want everything (or almost everything) in the memory – vsakos Jan 26 '15 at 21:23
  • Yes, it is slower. But you have no place to go here. You can only choose what you're going to bring into your memory once you're in the disk. So, that depends on what you want to accomplish. – vinitius Jan 26 '15 at 21:31
  • Ok, thanks. But what about storing the compressed image in ram? Is decompressing a jpeg very intensive operation? – vsakos Jan 26 '15 at 21:54
  • Yes, it's an intensive operation taking in account we have poor resources in mobile in general. There are some cool tips here: http://developer.android.com/training/displaying-bitmaps/index.html – vinitius Jan 26 '15 at 22:01