How do I display a list of images using the ListView? I am downloading the images at run time. The total number of images is not fixed.
-
2Hi. ever figured it out? would be great if you could share the solution – lostInTransit Feb 12 '09 at 15:54
-
1Published a sample code here http://stackoverflow.com/questions/541966/android-how-do-i-do-a-lazy-load-of-images-in-listview/3068012#3068012, should be helpful. – Fedor Jul 02 '10 at 01:47
8 Answers
I'd start with something like this (and if there is something wrong with my code, I'd of course appreciate any comment):
public class ItemsList extends ListActivity {
private ItemsAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.items_list);
this.adapter = new ItemsAdapter(this, R.layout.items_list_item, ItemManager.getLoadedItems());
setListAdapter(this.adapter);
}
private class ItemsAdapter extends ArrayAdapter<Item> {
private Item[] items;
public ItemsAdapter(Context context, int textViewResourceId, Item[] items) {
super(context, textViewResourceId, items);
this.items = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.items_list_item, null);
}
Item it = items[position];
if (it != null) {
ImageView iv = (ImageView) v.findViewById(R.id.list_item_image);
if (iv != null) {
iv.setImageDrawable(it.getImage());
}
}
return v;
}
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
this.adapter.getItem(position).click(this.getApplicationContext());
}
}
E.g. extending ArrayAdapter with own type of Items (holding information about your pictures) and overriden getView()
method, that prepares view for items within list. There is also method add()
on ArrayAdapter to add items to the end of the list.
R.layout.items_list
is simple layout with ListView
R.layout.items_list_item
is layout representing one item in list

- 24,084
- 23
- 95
- 173

- 869
- 7
- 8
-
1
-
2When you call findViewById on a View, it finds a child view; since you get different views with getView(), it finds a different child view every time. – Shawn Lauzon Aug 22 '11 at 17:33
-
could you share how the getImage() method looks like.. i am getting the following error - The method setImageResource(int) in the type ImageView is not applicable for the arguments (ImageView) – Harsha M V Nov 20 '11 at 10:03
-
@HarshaMV you should be passing a drawable resource, not a View itself, it should be something from R.drawable – victorcampos Jan 10 '12 at 17:30
-
You dont't need 'Items[]' inside ArrayAdapter - ArrayAdapter itself works as ArrayList already - use `add` to put items to it and `get` to fetch them. – aragaer Aug 13 '13 at 10:19
-
Had to use ...(LayoutInflater)getContext().getSystemService... in ItemsAdapter. – bluedot Jun 06 '17 at 23:27
package studRecords.one;
import java.util.List;
import java.util.Vector;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.net.ParseException;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class studRecords extends ListActivity
{
static String listName = "";
static String listUsn = "";
static Integer images;
private LayoutInflater layoutx;
private Vector<RowData> listValue;
RowData rd;
static final String[] names = new String[]
{
"Name (Stud1)", "Name (Stud2)",
"Name (Stud3)","Name (Stud4)"
};
static final String[] usn = new String[]
{
"1PI08CS016","1PI08CS007","1PI08CS017","1PI08CS047"
};
private Integer[] imgid =
{
R.drawable.stud1,R.drawable.stud2,R.drawable.stud3,
R.drawable.stud4
};
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mainlist);
layoutx = (LayoutInflater) getSystemService(
Activity.LAYOUT_INFLATER_SERVICE);
listValue = new Vector<RowData>();
for(int i=0;i<names.length;i++)
{
try
{
rd = new RowData(names[i],usn[i],i);
}
catch (ParseException e)
{
e.printStackTrace();
}
listValue.add(rd);
}
CustomAdapter adapter = new CustomAdapter(this, R.layout.list,
R.id.detail, listValue);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
}
public void onListItemClick(ListView parent, View v, int position,long id)
{
listName = names[position];
listUsn = usn[position];
images = imgid[position];
Intent myIntent = new Intent();
Intent setClassName = myIntent.setClassName("studRecords.one","studRecords.one.nextList");
startActivity(myIntent);
}
private class RowData
{
protected String mNames;
protected String mUsn;
protected int mId;
RowData(String title,String detail,int id){
mId=id;
mNames = title;
mUsn = detail;
}
@Override
public String toString()
{
return mNames+" "+mUsn+" "+mId;
}
}
private class CustomAdapter extends ArrayAdapter<RowData>
{
public CustomAdapter(Context context, int resource,
int textViewResourceId, List<RowData> objects)
{
super(context, resource, textViewResourceId, objects);
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder holder = null;
TextView title = null;
TextView detail = null;
ImageView i11=null;
RowData rowData= getItem(position);
if(null == convertView)
{
convertView = layoutx.inflate(R.layout.list, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
}
holder = (ViewHolder) convertView.getTag();
i11=holder.getImage();
i11.setImageResource(imgid[rowData.mId]);
title = holder.gettitle();
title.setText(rowData.mNames);
detail = holder.getdetail();
detail.setText(rowData.mUsn);
return convertView;
}
private class ViewHolder
{
private View mRow;
private TextView title = null;
private TextView detail = null;
private ImageView i11=null;
public ViewHolder(View row)
{
mRow = row;
}
public TextView gettitle()
{
if(null == title)
{
title = (TextView) mRow.findViewById(R.id.title);
}
return title;
}
public TextView getdetail()
{
if(null == detail)
{
detail = (TextView) mRow.findViewById(R.id.detail);
}
return detail;
}
public ImageView getImage()
{
if(null == i11)
{
i11 = (ImageView) mRow.findViewById(R.id.img);
}
return i11;
}
}
}
}
//mainlist.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>

- 3,531
- 6
- 34
- 45
Here is the simple ListView with different images. First of all you have to copy the different kinds of images and paste it to the res/drawable-hdpi in your project. Images should be (.png)file format. then copy this code.
In main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<ListView
android:id="@+id/listview"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
create listview_layout.xml and paste this code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageView
android:id="@+id/flag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/hello"
android:paddingTop="10dp"
android:paddingRight="10dp"
android:paddingBottom="10dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp"
android:text="TextView1" />
<TextView
android:id="@+id/cur"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="10dp"
android:text="TextView2" />
</LinearLayout>
In your Activity
package com.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class SimpleListImageActivity extends Activity {
// Array of strings storing country names
String[] countries = new String[] {
"India",
"Pakistan",
"Sri Lanka",
"China",
"Bangladesh",
"Nepal",
"Afghanistan",
"North Korea",
"South Korea",
"Japan"
};
// Array of integers points to images stored in /res/drawable-hdpi/
//here you have to give image name which you already pasted it in /res/drawable-hdpi/
int[] flags = new int[]{
R.drawable.image1,
R.drawable.image2,
R.drawable.image3,
R.drawable.image4,
R.drawable.image5,
R.drawable.image6,
R.drawable.image7,
R.drawable.image8,
R.drawable.image9,
R.drawable.image10,
};
// Array of strings to store currencies
String[] currency = new String[]{
"Indian Rupee",
"Pakistani Rupee",
"Sri Lankan Rupee",
"Renminbi",
"Bangladeshi Taka",
"Nepalese Rupee",
"Afghani",
"North Korean Won",
"South Korean Won",
"Japanese Yen"
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Each row in the list stores country name, currency and flag
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(int i=0;i<10;i++){
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("txt", "Country : " + countries[i]);
hm.put("cur","Currency : " + currency[i]);
hm.put("flag", Integer.toString(flags[i]) );
aList.add(hm);
}
// Keys used in Hashmap
String[] from = { "flag","txt","cur" };
// Ids of views in listview_layout
int[] to = { R.id.flag,R.id.txt,R.id.cur};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.listview_layout, from, to);
// Getting a reference to listview of main.xml layout file
ListView listView = ( ListView ) findViewById(R.id.listview);
// Setting the adapter to the listView
listView.setAdapter(adapter);
}
}
This is the full code.you can make changes to your need... Comments are welcome

- 11
- 3

- 41
- 2
Six years on, this is still at the top for some searches. Things have changed a lot since then. Now the defacto standard is more or less to use Volley and the NetworkImageView which takes care of the heavy lifting for you.
Assuming that you already have your Apaters, Loaders and ListFragments setup properly, this official google tutorial explains how to use NetworkImageView to load the images. Images are automatically loaded in a background thread and the view updated on the UI thread. It even supports caching.

- 52,766
- 11
- 101
- 134
-
1Volley is so much better than manually rolling all that code over and over. We had all the functionality we needed in under an hour. – esegura Nov 24 '15 at 22:35
-
I came up with a solution that I call “BatchImageDownloader” that has served well. Here’s a quick summary of how it is used:
Keep a global HashMap (ideally in your Application object) that serves as a cache of drawable objects
In the getView() method of your List Adapter, use the drawable from the cache for populating the ImageView in your list item.
Create an instance of BatchImageDownloader, passing in your ListView Adapter
Call addUrl() for each image that needs to be fetched/displayed
When done, call execute(). This fires an AsyncTask that fetches all images, and as each image is fetched and added to the cache, it refreshes your ListView (by calling notifyDataSetChanged())
The approach has the following advantages:
- A single worker thread is used to fetch all images, rather than a separate thread for each image/view
- Once an image is fetched, all list items that use it are instantly updated
- The code does not access the Image View in your List Item directly – instead it triggers a listview refresh by calling notifyDataSetChanged() on your List Adapter, and the getView() implementation simply pulls the drawable from the cache and displays it. This avoids the problems associated with recycled View objects used in ListViews.
Here is the source code of BatchImageDownloader:
package com.mobrite.androidutils;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.widget.BaseAdapter;
public class BatchImageDownloader extends AsyncTask<Void, Void, Void> {
List<String> imgUrls = new ArrayList<String>();
BaseAdapter adapter;
HashMap<String, Drawable> imageCache;
public BatchImageDownloader(BaseAdapter adapter,
HashMap<String, Drawable> imageCache) {
this.adapter = adapter;
this.imageCache = imageCache;
}
public void addUrl(String url) {
imgUrls.add(url);
}
@Override
protected Void doInBackground(Void... params) {
for (String url : imgUrls) {
if (!imageCache.containsKey(url)) {
Drawable bm = downloadImage(url);
if (null != bm) {
imageCache.put(url, bm);
publishProgress();
}
}
}
return null;
}
@Override
protected void onProgressUpdate(Void... values) {
adapter.notifyDataSetChanged();
}
@Override
protected void onPostExecute(Void result) {
adapter.notifyDataSetChanged();
}
public Drawable downloadImage(String url) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try {
HttpResponse response = httpClient.execute(request);
InputStream stream = response.getEntity().getContent();
Drawable drawable = Drawable.createFromStream(stream, "src");
return drawable;
} catch (ClientProtocolException e) {
e.printStackTrace();
return null;
} catch (IllegalStateException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}

- 432
- 1
- 4
- 13
-
-
Link died end of 2014 it looks like. Here's a wayback machine link: https://web.archive.org/web/20131030043626/http://agileyogi.com/lazy-loading-images-in-a-listview/ – Anubian Noob Jul 18 '15 at 15:59
-
The original answer link points to some search engine kinda thing in some other language. Don't click it. – We are Borg Jul 20 '15 at 14:18
-
Edited, removed link and included code and description in the answer – Thinkisto Jul 21 '15 at 09:01
File name should match the layout id which in this example is : items_list_item.xml in the layout folder of your application
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<ImageView android:id="@+id/R.id.list_item_image"
android:layout_width="100dip"
android:layout_height="wrap_content" />
</LinearLayout>
To get the data from the database, you'd use a SimpleCursorAdapter
.
I think you can directly bind the SimpleCursorAdapter
to a ListView
- if not, you can create a custom adapter class that extends SimpleCursorAdapter with a custom ViewBinder
that overrides setViewValue
.
Look at the Notepad tutorial to see how to use a SimpleCursorAdapter
.

- 76,767
- 18
- 98
- 146
We need to implement two layouts. One to hold listview and another to hold row item of listview. Implement your own custom adapter. Idea is to include one textview and one imageview.
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View single_row = inflater.inflate(R.layout.list_row, null,
true);
TextView textView = (TextView) single_row.findViewById(R.id.textView);
ImageView imageView = (ImageView) single_row.findViewById(R.id.imageView);
textView.setText(color_names[position]);
imageView.setImageResource(image_id[position]);
return single_row;
}
Next we implement functionality in main activity to include images and text data dynamically during runtime. You can pass dynamically created text array and image id array to the constructor of custom adapter.
Customlistadapter adapter = new Customlistadapter(this, image_id, text_name);

- 170,088
- 45
- 397
- 571