Android: Asynchronously download images
By Anatoly Mironov
In the Malmöfestivalen for Android where I participate we wanted to show thumbnails of events in lists. We have urls of thumbnails from Malmofestivalen API. This information is stored in a sqlite database and a SimpleCursorAdapter is used for getting the events from the database. It is possible to bind the urls to ImageView objects (by downloading the stream: 1, 2, 3). The problem is in a listactivity with many images it will freeze. So it must be an AsyncTask, and it should be some kind of local cache to avoid loading same images over and over again. Fortunately there is already ImageDownloader class provided in the android blog post: Multithreading For Performance . The next step is to create custom adapter and extend from SimpleCursorAdapter: EventCursorAdapter, like described on Android-er and and SP-Technolab: [sourcecode language=“java”]public class EventCursorAdapter extends SimpleCursorAdapter { private final ImageDownloader imageDownloader = new ImageDownloader(); public EventCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to) { super(context, layout, c, from, to); imageDownloader.setMode(ImageDownloader.Mode.NO_DOWNLOADED_DRAWABLE); } @Override public View getView(int position, View convertView, ViewGroup parent) { View row = super.getView(position, convertView, parent); Cursor cursor = getCursor(); cursor.moveToPosition(position); ImageView iv = (ImageView) row.findViewById(R.id.eventitemrowimage); String url = cursor.getString(cursor.getColumnIndex(EventProvider.EVENT_KEY_URISMALLIIMAGE)); if (url.length() > 0) { imageDownloader.download(url, iv); } String start = cursor.getString(cursor.getColumnIndex(EventProvider.EVENT_KEY_STARTDATE)); String end = cursor.getString(cursor.getColumnIndex(EventProvider.EVENT_KEY_ENDDATE)); String dateString = DateHelper.createShortDateResume(start, end); TextView tv = (TextView) row.findViewById(R.id.eventitemrowtimeresume); tv.setText(dateString); return row; } }[/sourcecode] In this code the view is created by the super class and then it is modified, the alternative is to “inflate the view” completely self. The result is an event list which opens directly and loads thumbnails asynchronously: listactivity with images
Comments from Wordpress.com
Justin Cooney - Apr 4, 2012
A very interesting example of how to download images asynchronously!
Anatoly Mironov - Apr 4, 2012
Thank you Justin! Glad you liked it. I think async is the only option we have nowadays :)
Anatoly Mironov - Apr 1, 2014
Good question. I have not thought about it. The view I had had only the vertical orientation. What happens on orientation change? Gets the view redrawed then?
matias elorriaga - Apr 1, 2014
this is an excellent article, but I have one question.. how do we handle device orientation changes? every time this happens, the listview re-download the images..