Question

I have implemented a simple infinite scrolling GridView on Android. I have the following components:

  1. a GridView with a onScrollListener, whenever the GridView is scrolled to the very bottom, I kick off an AsyncTask to load more items into my Adapter.
  2. an adapter that appends the items fetched from the AsyncTask, and fires notifyDataChanged() so the GridView can refresh itself.

This seems to work fine except in this case the adapter is growing indefinitely...I mean I keep appending items to this adapter whenever the user scrolls to the end, this seems to be a memory problem.

What's the proper way of implementing an endless adapter? I am looking for concepts, not a third party jar that does it for me.

Thanks

solution
The marked answer has the right theory. My implementation of it backs up the loaded data into a sqllite database, so the overall flow is: download data from the internet in a thread, parse and store the data into database in a thread, fire notifyDataChanged on UI thread.
The adapter's getCount() method simply does a select count(id) from the database, and it retrieves a batch of objects at once from the database into memory for the adapter to use.

Was it helpful?

Solution

Yes, generally if your GridView is infinite, then your Adapter is infinite. If you have a naive implementation of just loading more data into memory then you will certainly run into a memory problem at some point. To get around this, you will have to release old data at some point.

Assuming your adapter has access to some "infinite" store where it gets its data from (oftentimes the internet), you could consider setting a maximum size (either in bytes or in item count) of data to hold in memory for your adapter. When you get past the maximum size, you can purge old items from memory. If these old items are requested again, you load them again from the infinite store instead of from memory (and probably other old items are purged from memory).

This means your GridView items are built from an Adapter which stores data in some sort of cache (LruCache could be useful here) which is backed by some (probably external) store. You could also put a disk cache between the memory cache and the external store.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top