Wednesday, April 22, 2015

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/AVvXsEh45-l11b9CxlWURRdH3KtwaQYMf7lvCjGjhbao52Wi5r7qrd0Xfth6xTflusBxKTwJe8172h0klxldaYUJESZzyz5prDEKN2dtHrH4IaD-9OTdx1CSkein7e0FMVFBv4WVw4COAQx5vD4/s1600/_01.png",
   "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEggAIxdysN9SF1x7kU-8qHa3-ut75IlMneUrZj008Rnw1uZoRt8cEc08GNuBOrH1oYvERfoGKANoo1GVVAEQMOcYUt3THG0WJXl0nUyv1pYyot_fLYTfBpOvIU4LgKrRdqKbcjNpDAqZjk/s1600/_02.png",
   "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEicQXPrH8ePv6XTHC-gVrwt5IODdKqiaoZUiJpDZBOeKbKt1zS1deLLOIdpxLYCXCnuXTIP2ZaCFsLY49sDOmda6-S6kHJBaCrbzNlsXornSIPOW3J__TaAYj4mN6kniZIHnKlOD7XSRzE/s1600/_03.png",
   "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEibJPrKh6gadVz_Lk9WB88l2h1eFjXzwzltzT3qawdhx-whIker16zNLjjdOlZK6ZQb-g-Gh8f6KQgKNz3LEM6lV_uTfRjB_Jqyijx0UhXCDiBk2PmGeG9JepX3SKtG9smYIgCxoz6YBcg/s1600/_04.png",
   "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgJYw1j_8u6OyPr-X5kxKghanaf4uZgWykHGnR4T82FJ8X8KeVcZFT91aNR-mcUKYh8_VW4g6bC_VwskODH9yEu4Q3S_0bdtzx7fixquKWv0BVJGILN-b0vpvXGerWTPf-H6xqtmHPAq74/s1600/_05.png",
   "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEisebiSsu0boJ3EncEPMYnLj8MEvb2amGp0W4jrvTz-htJos8CHlUjtqALhC3Z1tS73zY1cKDn14WDJ0qqsIEova5rGxtKqfGw4jaPAWpUpWlM7OWrQrTthmZuXDlvONPUP_ixqypr1R5Y/s1600/_06.png",
   "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgxZwuI5jNXioK2PBfvFkhcyNj-qGTmnB8_pXATaGl5VwKWitoWAbe_OecmK-LimzJ95x_YmYjgrOY2xCLr9ScwzOalPC_1wx1l3rWvN-SKkYinS-LjQoei6OiuCA5Vhqz5XjEwrCfFv4A/s1600/_07.png",
   "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhN_NWFc1tGg7yOlyj_ytqlzlAeUyjL-EOehYIKwpjqIZFdpiFxFK292j5Nl2Nercsb0JVcMGk0BNJ_7DwShmOhzbtAOreQBxXV5Kf-PnxizNC-g-relCv2ojBgAHJHIRG_kE0-B1xVx2I/s1600/_08.png",
   "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhvnZ4Mucl5g31ikF1BFvcPP4L2ligLXcw71xjpTIgpgbw9ycf0kGWC_dE6asoXoQq4BOY-mdKQoe6dCUpTca5jMM2BBTjigDqbvvePkhx4hPkmHvhm7HlgYj5UMGZHmBbSCrleitJ2ekQ/s1600/_09.png",
   "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjM-Pv79aw3p7_5zjgN08vWs6_qx7QHGxVX9kofXoAoShjrURoMNk10AgH5intycrEB6o4nb215IqkeAUGjo7A8aBRFUe_052Vmn5cY7rIYyaxFCVbeJTADl0lYj4kD71t2psHKYAsk3Uw/s1600/_10.png",
   "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiQAPsubpaTgVDk1vkG8Ktml3nljEBbRfva7J3hqQ1QfJZ1wdKp9UIbm8-JNyCeHwmPFEGpZ5GEih6Zgn9giK3Gcfbka8Sbqfj-0VqvCUzu7w3JbZ6QTMwGmf10zil_xeDz0p6zPopN0nY/s1600/_11.png",
   "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEidlI97E_km-6-Yx-xqrccSG5TNH5e_RU-NTOesxP1SCQMMf2ft1TQrwIA8MnapXjPrLDuzaJDzD4Eni11C7dqTJAY37LympC128pGE0OyBSZzRhyphenhyphenPYxovNdmI_JgP8l0B5dVcoK_txhy4/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

No comments:

Post a Comment