I am using a custom CursorAdapter for a ListView to display some images and captions associated with those images. I am getting the images from the Internet.
The implementation produced significant lag in the UI when scrolling through items. This is because the getView() method of a ListView adapter can be called one or more times each time a ListView item comes into view – we are given no guarantees on when or how this method will be called. Therefore, downloading images within getView() was extremely inefficient, as each image was being downloaded by the UI thread as the ListView item came into view, and was usually downloaded repeatedly after that.
Today I’ll refactor my app to add asynchronous
lazy loading and caching of images. Some of the code included has been based on the excellent
demonstration provided by Github user
thest1. Through this example, I’ll demonstrate asynchronous operations in Android, using local storage for caching data, ViewHolders, and a few other advanced techniques for optimizing app performance.
Since all(downloading images) of this is happening on the UI thread, massive UI lag resulted, which would create a poor user experience for a production app. The root problems are:
- Images are being downloaded from the UI thread
- Images are being downloaded many, many more times than they need to be, since getView() is called as often as Android feels like calling it
So, what can we do?