0

I am building a gallery using a ViewPager. Every time a photo is downloaded I immediately cache it in mMemoryCache which is

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

As you can see sizeOf() returns the number if bytes used, which makes sense. My problem is that my ViewPager's adapter needs to know how many pages I have, which would be the number of objects in my cache.

Any ideas on how I can do it? thanks!

Yotam
  • 9,789
  • 13
  • 47
  • 68
  • Shouldn't your ViewPager show all the possible images, not just the ones that are downloaded? Just show nothing or a default image if it is not yet downloaded. Or what exactly is your intention? – SimonSays Nov 27 '13 at 22:54
  • Well the data base if too big so I just download a bunch of images, and when the user gets close to the adapter's count I download more and update the count, and for that I need to know how many images I cached – Yotam Nov 27 '13 at 23:10

1 Answers1

1

I think you should rethink your approach. Usually, when you use some kind of paging (i mean data paging, not the ViewPager), you first add a certain fixed number of items to your Adapter. You can either start downloading the required resources right away, or wait until you really need them. Check in Adapter.onCreateView() if the resource is already downloaded and cached. If yes, get it from there, if not, start an asynchronous download and add the image to the view as soon as you got it. Show a placeholder in the meantime.

When you reach the last item in your adapter, add another batch to it and everything starts over again.

If you really want to know what items are in your LRUCache, override put() and entryRemoved(). There you know what items get added or evicted from the cache. I would advise against this method though.

SimonSays
  • 10,867
  • 7
  • 44
  • 59