Async load image from internet to ListView

Android example to load images in AsyncTask from internet to ListView.


MainActivity.java
package com.example.androidasynclist;

import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Arrays;

import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

final static String src[] = {
"https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjxYA2TP59zm7hoyWluyguN9yrFlwVoNSPcLkbx_oRavCs01RIt9fApucGR4uO0WG_WcvzJxaAeP6fc4BESnP-YVgVLwMhHm6wxp5nF-iCBwZq-1YNYQV0sqLXGvSMAO9x4PPF91zzqgNg/s1600/_01.png",
"https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh6MQOBV3maBw2Hr8iMrl2r6actOucVvrDBlULuGdpxLSzM5xsk465B95ABh0KRGaOfpJ6z35ezPSbwydnaRFSLC6w2FqPRy3GJEJnuqrBAlv3ddtQPnVPbNPOaXWcOnKLtOFmFWTAXcrw/s1600/_02.png",
"https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiRYR1eDlEMc8cZvK3lNboDLeBG-7jTDFz_BZIi6vBW7gxF3JZzgTleQRg1E10_WY4OwK-ciDJ67CvRA1FbSHm-0_3G_rycJuxEH6UQ17XbFG4i4tbFD5uC_EKIxBmjeSpUtqP0yV0nrDM/s1600/_03.png",
"https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgxhrYhFYv9bdbcVi-F3wulHyEb6M2uc-i3NgAeCdRO5Fi438eAQiPM3hvILUeLW_QbGckcaOVGeT60L1Yfq2Qn78GtdPRQLPAKk095tQaADSUfDi8fCee-gwCTmAeoBvqH_ESL_7mgNgw/s1600/_04.png",
"https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh9PgwYx-heZQKNnAtgmgX3TkgbeMy_A8m1czwaDW-bKDjJZim2M9xrrFLCGN1vqofkpJlvr3nSfePZ8X-ZO3fiPm22LEHSFp8Gj_3hh61RcXE3q4IG7ZImcI1i8VXOZxIE1NsXqahx-lE/s1600/_05.png",
"https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhOh3dW6lzIGC2XFdmRoqfmwgo3d2LUmT0bDITrjKrLjPn69OvSE9YvQmrSHNxqdymej5cnGMVUdaUCFa-q92qC1G1NS88znI-RUi80p_Qs-8U9tOEMUBndnD0ReqbJwuvM3dwAM6FCr18/s1600/_06.png",
"https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgjA20FPeKeSLUQdTKnxLeKiPLzBC0gOCUayYeJUvqR7d_A2rlIuRSh6PAeuIyiFNwvlqPGq_o4hEy91D69bQmu1LjZOOrs0EpIdPhpOaYw-XcUVfEi0_0cMqpsb5gsYMxMuaCJ5gQwbeo/s1600/_07.png",
"https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj06GkHwiiKC3GrbeVXgeH8b6XKOUTGfjxXJxhy9tIF3Bs70mZMOPPF04Ul1oBOG-zhT2VkWH9ZLuuE_9AiGdmETXAapaL69XqO_LxjQSlBi7ObeYy5KIPjCVvIAqMBApLwqe4GiQWZNLA/s1600/_08.png",
"https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiq0TH0q109iqTp9Cn6je_5K_pZKfJqusUbwfZRJCVMmnJBjqC_aXeCviCbmD4WvxEBqRAqv-cKOAJDCM2bHSwXVVD6KTiQCgfE5veO2U9z_L8QBCNAoX2yDYmXXJc8tLJXcdF-PUdrORM/s1600/_09.png",
"https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgPW-Q4nZXz2Ng2CojKUHE0O4EtOjW6165r8y_ahH4izvpsfXxOLR1Vf17nfzoB7Hzkn7cn-KcA9ZbzZ1bNMNtCj_qZRaBH93Vkgo8ErWmGlCn481-ck14Ynf8k-rnKM-1z8_s7i-6rtVg/s1600/_10.png",
"https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhFHK6TzK9DbzUVfpJGd5xnXGSThaKCudLUh_BOivIZEpGPS9AEAowqTpayrDscuUrYMJ_W3xlL_GY11xJtq8kBAPqmEquag1FK846sbMD0uEDrPfu-LcMY-ts12RK2YCWX0_28_5mx7zY/s1600/_11.png",
"https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhpsAKQi-eHtHDKbTEZgzAjh0ieCWsUhbFBDYlV5VPn_ACzuFSs20uvESD-BLXDlTr5KbnmhK8JGx7mxufCtUzI31fsB5KZNN1TJc21J-6_ENdJZlCRIpknAFNxaercy7ASQiAi_yeRwJ4/s1600/_12.png" };

ListView imageList;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

imageList = (ListView) findViewById(R.id.imagelist);
ArrayList<String> srcList = new ArrayList<String>(Arrays.asList(src));
imageList.setAdapter(new CustomListAdapter(this, srcList));
}

// ----------------------------------------------------

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

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

@Override
public int getCount() {
return listData.size();
}

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

@Override
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.row, null);
holder = new ViewHolder();
holder.icon = (ImageView)convertView.findViewById(R.id.icon);
holder.text = (TextView)convertView.findViewById(R.id.text);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}

holder.text.setText(String.valueOf(position));

if (holder.icon != null) {
new BitmapWorkerTask(holder.icon).execute(listData.get(position));
}
return convertView;
}

class ViewHolder {
ImageView icon;
TextView text;
}
}

// ----------------------------------------------------
// Load bitmap in AsyncTask
// ref:
// http://developer.android.com/training/displaying-bitmaps/process-bitmap.html
class BitmapWorkerTask extends AsyncTask<String, Void, Bitmap> {
private final WeakReference<ImageView> imageViewReference;
private String imageUrl;

public BitmapWorkerTask(ImageView imageView) {
// Use a WeakReference to ensure the ImageView can be garbage
// collected
imageViewReference = new WeakReference<ImageView>(imageView);
}

// Decode image in background.
@Override
protected Bitmap doInBackground(String... params) {
imageUrl = params[0];
return LoadImage(imageUrl);
}

// Once complete, see if ImageView is still around and set bitmap.
@Override
protected void onPostExecute(Bitmap bitmap) {
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}

private Bitmap LoadImage(String URL) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
}
return bitmap;
}

private InputStream OpenHttpConnection(String strURL)
throws IOException {
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();

try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("GET");
httpConn.connect();

if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
} catch (Exception ex) {
}
return inputStream;
}
}
}

/res/layout/activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.androidasynclist.MainActivity" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:autoLink="web"
android:text="http://android-er.blogspot.com/"
android:textStyle="bold" />

<ListView
android:id="@+id/imagelist"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />

</LinearLayout>

/res/layout/row.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >

<ImageView
android:id="@+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

</LinearLayout>

Permission of "android.permission.INTERNET" is needed in AndroidManifest.xml.



download filesDownload the files.

Related:
Load WebP from Internet and display in ListView