1. Introduction

As mobile devices are limited with memory, we must follow certain best practices to provide best performance and smooth user experience. Among set of best practices, the one holds 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 simple 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.

If you’re looking for downloading data from asynchronously from server, we recommend you to read through Android networking tutorial.

Async ListView Android Example

2. What is Android AsyncTask

AsyncTask enables you to implement MultiThreading without getting your hands dirty into threads. AsyncTask is easy to use, and it allows performing background operation in dedicated thread and passing the results back 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 basic characteristics of AsyncTask are as follows

  1. An asynchronous task is defined by 3 generic types, called ParamsProgress and Result, and 4 steps, called onPreExecutedoInBackgroundonProgressUpdate and onPostExecute.
  2. In onPreExecute you can define code, which need to be executed before background processing starts.
  3. 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.
  4. 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
  5. The onPostExecute() method handles results returned by doInBackground method.
  6. If an async task not using any types, then it can be marked as Void type.
  7. An running async task can be cancelled by calling cancel() 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.

3. Downloading image using AsyncTask

We had learnt the basics of AsyncTask. Let us take a glance at how to use it practically for downloading image asynchronously from web. To achieve this, let us create a new class and name it as ImageDownloaderTask.

The following code snippet expects the url of image as an parameter and initiate download image download request. Once download is over, it displays the bitmap on the image view.

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

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

    protected Bitmap doInBackground(String... params) {
        return downloadBitmap(params[0]);

    protected void onPostExecute(Bitmap bitmap) {
        if (isCancelled()) {
            bitmap = null;

        if (imageViewReference != null) {
            ImageView imageView = imageViewReference.get();
            if (imageView != null) {
                if (bitmap != null) {
                } else {
                    Drawable placeholder = imageView.getContext().getResources().getDrawable(R.drawable.placeholder);

4. Downloading image from web

Notice that, in the above step we are calling downloadBitmap() method but haven’t declared it yet. Let us create declare the  downloadBitmap method which takes care of loading image and returning the bitmap. Here we are using HttpURLConnection to download the stream from given url. Learn more about HttpURLConnection from our android networking tutorial.

private Bitmap downloadBitmap(String url) {
    HttpURLConnection urlConnection = null;
    try {
        URL uri = new URL(url);
        urlConnection = (HttpURLConnection) uri.openConnection();
        int statusCode = urlConnection.getResponseCode();
        if (statusCode != HttpStatus.SC_OK) {
            return null;

        InputStream inputStream = urlConnection.getInputStream();
        if (inputStream != null) {
            Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
            return bitmap;
    } catch (Exception e) {
        Log.w("ImageDownloader", "Error downloading image from " + url);
    } finally {
        if (urlConnection != null) {
    return null;

5. Creating custom ListView

Now that we understand the basics of AsyncTask, let us proceed with creating the custom list view in android. The focus of this tutorial is tried to image download. If you not familiar with creating custom list view in android, you can read our Android ListView tutorial.

5.1. Adding ListView to activity layout

For sake of simplicity our activity layout contains a simple ListView that covers the total available width and height of the device. Create a new file activity_main.xml in layout directory.

<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"   

5.2. Create list view activity

Let us now create a new activity class MainActivity.java in your project src directory and paste the following code. We will complete this activity in Section 3.5

public class MainActivity extends Activity {

	public void onCreate(Bundle savedInstanceState) {

5.3. Create list row layout

Now let us focus on the layout for list view row item. As you can notice form the above screenshot, we will use RelativeLayout for building a simple list row view. Crete a new file list_row_layout.xml file in layout directory and paste the following code blocks.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

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

        android:textStyle="bold" />

        android:layout_toRightOf="@id/thumbImage" />

        android:layout_alignParentRight="true" />


5.4. Creating custom list adapter

Adapter is acts as a bridge between data source and adapter views such as ListView, GridView. Adapter iterates through the data set from beginning till the end and generate Views for each item in the list.

Create a new class named CustomListAdapter and extend it from BaseAdapter. Visit here to learn more about android adapters.

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(R.id.title);
			holder.reporterNameView = (TextView) convertView.findViewById(R.id.reporter);
			holder.reportedDateView = (TextView) convertView.findViewById(R.id.date);
			holder.imageView = (ImageView) convertView.findViewById(R.id.thumbImage);
		} 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;

5.5. Using list view adapter

Now that we have the list view and adapter class ready. Let us proceed to complete the MainActivity class. The following code snippet is used to initialize the list view and assign the custom adapter to it.

public class MainActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {

        ArrayList<ListItem> listData = getListData();

        final ListView listView = (ListView) findViewById(R.id.custom_list);
        listView.setAdapter(new CustomListAdapter(this, listData));
        listView.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> a, View v, int position, long id) {
                ListItem newsData = (ListItem) listView.getItemAtPosition(position);
                Toast.makeText(MainActivity.this, "Selected :" + " " + newsData, Toast.LENGTH_LONG).show();

    private ArrayList<ListItem> getListData() {
        ArrayList<ListItem> listMockData = new ArrayList<ListItem>();
        String[] images = getResources().getStringArray(R.array.images_array);
        String[] headlines = getResources().getStringArray(R.array.headline_array);

        for (int i = 0; i < images.length; i++) {
            ListItem newsData = new ListItem();
            newsData.setReporterName("Pankaj Gupta");
            newsData.setDate("May 26, 2013, 13:35");
        return listMockData;

Notice that, getListData() method in the activity is used to create some dummy list data for the list view. To make this example simple, we are using the string arrays defined in the strings.xml resource file. But in realtime you might download the data from server or get it from any other sources.

Add the following string array declarations to string.xml file.

<?xml version="1.0" encoding="utf-8"?>
    <string name="app_name">Async ListView</string>
    <array name="images_array">

    <array name="headline_array">
        <item>Dance of Democracy</item>
        <item>Major Naxal attacks in the past</item>
        <item>BCCI suspends Gurunath pending inquiry </item>
        <item>Life convict can`t claim freedom after 14 yrs: SC</item>
        <item>Indian Army refuses to share info on soldiers mutilated at LoC</item>
        <item>French soldier stabbed; link to Woolwich attack being probed</item>
        <item>Life convict can`t claim freedom after 14 yrs: SC</item>

5. Download Complete Example


This article is about: Android UI, ListView,


A blogger, a bit of tech freak and a software developer. He is a thought leader in the fusion of design and mobile technologies. He is the author of Xamarin Mobile Application Development for Android Book (goo.gl/qUZ0XV3), DZone MVB and founder of stacktips.com.


Please note: We reserve the right to delete comments that contains snarky remarks, offensive or off-topic. To know more read our comments policy.