Asynchronous Image Loader in Android ListView

1. Introduction

As mobile devices are limited with memory, we must follow certain best practices to provide best performance smooth user experience. Among set of best practices, the one holds most priority is to take the long running heavy operations off the main thread.

Any long running tasks or heavy operations are usually performed in a different thread, to make sure your main thread does the minimum amount of work. Example of a typical long running tasks could be network operations, reading files form memory, animations, etc.

In this tutorial, we will create a sample ListView in Android that downloads data  asynchronously from the internet using a AsyncTask. As you can see in the screenshot below, the ListView contains a image thumbnails on each row, we will download the images asynchronously form server.

asynchronous image loader in Android ListView

1. What is Android AsyncTask

AsyncTask enables you to implement MultiThreading without get Hands dirty into threads. AsyncTask is easy to use, and it allows performing background operation in background thread and passing the results on the UI thread. If you are doing something isolated related to UI, for example downloading data for List view, go ahead and use AsyncTask.

Some of the AsyncTask characteristics are as follows

  1. AsyncTasks should ideally be used for short operations
  2. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.
  3. In onPreExecute you can define code, which need to be executed before background processing starts.
  4. The doInBackground() method contains the code which needs to be executed in background, here in doInBackground we can send results to multiple times to event thread by publishProgress() method, to notify background processing has been completed we can return results simply.
  5. The onProgressUpdate() method receives progress updates from doInBackground method, which is published via publishProgress method, and this method can use this progress update to update event thread
  6. The onPostExecute() method handles results returned by doInBackground method.
  7. If an async task not using any types, then it can be marked as Void type.
  8. An running async task can be cancelled by calling cancel(boolean) method.

The generic types used by AsyncTask are

  • Params, the type of the parameters sent to the task upon execution
  • Progress, the type of the progress units published during the background computation.
  • Result, the type of the result of the background computation.

2. Creating a Custom ListView

1.1. Define List Row Layout

In this tutorials we are planning to crate a ListView similar to the image shown below. You can use a RelativeLayout for this.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""
    android:orientation="horizontal" >

        android:background="@drawable/list_placeholder" />

        android:typeface="sans" />

        android:textSize="12sp" />

        android:textSize="12sp" />


1.2. Creating A Custom Adapter

public class CustomListAdapter extends BaseAdapter {
	private ArrayList listData;
	private LayoutInflater layoutInflater;

	public CustomListAdapter(Context context, ArrayList listData) {
		this.listData = listData;
		layoutInflater = LayoutInflater.from(context);

	public int getCount() {
		return listData.size();

	public Object getItem(int position) {
		return listData.get(position);

	public long getItemId(int position) {
		return position;

	public View getView(int position, View convertView, ViewGroup parent) {
		ViewHolder holder;
		if (convertView == null) {
			convertView = layoutInflater.inflate(R.layout.list_row_layout, null);
			holder = new ViewHolder();
			holder.headlineView = (TextView) convertView.findViewById(;
			holder.reporterNameView = (TextView) convertView.findViewById(;
			holder.reportedDateView = (TextView) convertView.findViewById(;
			holder.imageView = (ImageView) convertView.findViewById(;
		} else {
			holder = (ViewHolder) convertView.getTag();

		NewsItem newsItem = (NewsItem) listData.get(position);
		holder.reporterNameView.setText("By, " + newsItem.getReporterName());

		if (holder.imageView != null) {
			new ImageDownloaderTask(holder.imageView).execute(newsItem.getUrl());
		return convertView;

	static class ViewHolder {
		TextView headlineView;
		TextView reporterNameView;
		TextView reportedDateView;
		ImageView imageView;

1.3. Adding ListView to activity

Main Activity Layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""
    android:orientation="vertical" >

        android:listSelector="@drawable/list_selector_flatcolor" />


Here is my activity code

public class MainActivity extends Activity {

	public void onCreate(Bundle savedInstanceState) {

		ArrayList image_details = getListData();
		final ListView lv1 = (ListView) findViewById(;
		lv1.setAdapter(new CustomListAdapter(this, image_details));
		lv1.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> a, View v, int position, long id) {
				Object o = lv1.getItemAtPosition(position);
				NewsItem newsData = (NewsItem) o;
				Toast.makeText(MainActivity.this, "Selected :" + " " + newsData,

	private ArrayList getListData() {
		ArrayList results = new ArrayList();
		NewsItem newsData = new NewsItem();
		newsData.setHeadline("Dance of Democracy");
		newsData.setReporterName("Pankaj Gupta");
		newsData.setDate("May 26, 2013, 13:35");
                //Add some more dummy data to test this app.
		return results;

3. Asynchronous ListView Example

3.1. Downloading Image From Web

static Bitmap downloadBitmap(String url) {
	final AndroidHttpClient client = AndroidHttpClient.newInstance("Android");
	final HttpGet getRequest = new HttpGet(url);
	try {
		HttpResponse response = client.execute(getRequest);
		final int statusCode = response.getStatusLine().getStatusCode();
		if (statusCode != HttpStatus.SC_OK) {
			Log.w("ImageDownloader", "Error " + statusCode
					+ " while retrieving bitmap from " + url);
			return null;

		final HttpEntity entity = response.getEntity();
		if (entity != null) {
			InputStream inputStream = null;
			try {
				inputStream = entity.getContent();
				final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
				return bitmap;
			} finally {
				if (inputStream != null) {
	} catch (Exception e) {
		// Could provide a more explicit error message for IOException or
		// IllegalStateException
		Log.w("ImageDownloader", "Error while retrieving bitmap from " + url);
	} finally {
		if (client != null) {
	return null;

3.2. Downloading Image Using AsyncTask

class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {
	private final WeakReference imageViewReference;

	public ImageDownloaderTask(ImageView imageView) {
		imageViewReference = new WeakReference(imageView);

	// Actual download method, run in the task thread
	protected Bitmap doInBackground(String... params) {
		// params comes from the execute() call: params[0] is the url.
		return downloadBitmap(params[0]);

	// Once the image is downloaded, associates it to the imageView
	protected void onPostExecute(Bitmap bitmap) {
		if (isCancelled()) {
			bitmap = null;

		if (imageViewReference != null) {
			ImageView imageView = imageViewReference.get();
			if (imageView != null) {

				if (bitmap != null) {
				} else {



4. Output

5. Download Complete Example

Here you can download complete eclipse project source code from GitHub.

Download Code


6. References

A blogger, a bit of tech freak and a software developer. He is a thought leader in the fusion of design and mobile technologies. Follow him on Twitter or Google plus.

  • 杰民 赵

    down code link failure , you can come here

    • JavaTechig

      Yes it is currently taking to github link. The project is available on git.

  • peeyush singhal

    hello sir, i have a problem when i am running this application it shows only R.drawable.list_placeholde image. How can i solve this problem please suggest me??

  • bbb


  • ali AS

    Hi sir,Its a great tutuorial but link is broken.Could you provide a new one please


    hey plz give me the download link

  • Nagul

    this wont work correctly. Since you are using viewholder the views are recycled so if your asynctask is downloading an image and you scroll the list down, you wound end up with a wrong image at the wrong place.

    • Milan Maharjan

      yep, he’s right

  • Gabriel Peixoto

    I changed the size of images to 300dp. So, I found a bug. The List showed repeated images and in wrong position.

  • Kevin

    Hello, thanks for this code, but unfortunately I have a problem. GetView method is not called although my size is not null. Can you help me?

  • Michael

    Hey, Could you give a link to github ?? I’ve liked this article but the content is still locked :/ It ll be very helpful to me.

  • Nilanchala Panigrahy

    Can you clear with your question. I cant guess what you asking..

  • avo28

    hello, thanks for this tutorial I worked perfect, but I have a problem, I’m using Spanish text, and accepted and the letter “Ñ” default character out with strangers, because you use clear text. java and do not know how to bring it from string. xml, I could tell how to fix this .. am newbie please calmly .. Note: I’m sorry for bad translation yet translating

  • avo28

    hola, gracias por este tutorial me funciono perfecto, pero tengo un problema, estoy utilizando texto en español, y sus aceptos y la letra “Ñ” sale con carcateres extraños, obvio porque usas texto en .java y no se como traerlo desde string.xml, me podrian decir como solucionar esto.. por favor soy novato con calma.. nota: estoy traduciendo perdon por mala traducion

  • Jyotika

    nice tutorial… its is easy to understand :)

  • Alejandro Casanova

    Thanks, excellent tutorial. The solution works just fine, but I have a problem when loading contact images, when I scroll the ListView the imageview of a row begins to change from the first contact image until de last one that was once in that position. I tried to initially put the default image to show but it only appears for a short time, then begins to change until the last one finishes loading.

    Here is my modification, but it doesn’t solves the problem completely.

    if (holder.image != null) {



    new ImageDownloaderTask(holder.image).execute(contact);


    How to avoid Imageview from reloading until the scrolling stops showing only a default image?


  • Art Match

    Thank you for sharing. It helped me..

  • Akuma Manalo

    hi Sir,thanks for this tutorial,I would like to ask how to insert the current date automatically in listview? thanks

    • javatechig

      You can call getCurrentTime method from getView method.


      public String getCurrentTime() {
      SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //dd/MM/yyyy
      Date now = new Date();
      String strDate = sdfDate.format(now);
      return strDate;

      • Akuma Manalo

        thanks this works =)