Universal Image Loader in Android

Introduction

 
This article explains the Universal Image Loader. The Universal Image Loader allows you to set various image view options. You can load the image from a URL at runtime using this. The advantage of using this is that you need not store all the images you want to use in your project (in drawable). This saves memory. In large projects where memory management is crucial, using Universal Image Loader is a good idea.
 
Step 1
 
You will need to include "universal-image-loader-1.7.0.jar" from the "library" zip, provided above, as a library in your project. Copy the jar file provided to the clipboard and paste it on the "libs" in your Eclipse project.
 
This jar contains the main functionalities that we will be using. 
 
Step 2
 
First, we will make an application class that will set the basic configurations.
 
Right-click on your package name then select "New" -> "Class". Name it "App" and add the following code to it:
  1. package com.chhavi.universalimageloader;  
  2.    
  3. import android.app.Application;  
  4. import android.content.Context;  
  5. import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;  
  6. import com.nostra13.universalimageloader.core.ImageLoader;  
  7. import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;  
  8. import com.nostra13.universalimageloader.core.assist.QueueProcessingType;  
  9.    
  10. public class App extends Application {  
  11.     @Override  
  12.     public void onCreate() {  
  13.    
  14.         super.onCreate();  
  15.         initImageLoader(getApplicationContext());  
  16.     }  
  17.    
  18.     public static void initImageLoader(Context context) {  
  19.         
  20.         ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)  
  21.                 .threadPriority(Thread.NORM_PRIORITY - 2)  
  22.                 .denyCacheImageMultipleSizesInMemory()  
  23.                 .discCacheFileNameGenerator(new Md5FileNameGenerator())  
  24.                 .tasksProcessingOrder(QueueProcessingType.LIFO)  
  25.                 .enableLogging()  
  26.                 .build();  
  27.    
  28.         ImageLoader.getInstance().init(config);  
  29.     }  
Step 3
 
Open the "activity_main" layout file and add the following code to it:
  1. <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"  
  2.             android:layout_width="fill_parent"  
  3.             android:layout_height="fill_parent" >  
  4.    
  5.     <LinearLayout  
  6.             android:layout_width="fill_parent"  
  7.             android:layout_height="fill_parent"  
  8.             android:orientation="vertical" >  
  9.    
  10.         <TextView  
  11.                 android:layout_width="fill_parent"  
  12.                 android:layout_height="wrap_content"  
  13.                 android:gravity="center"  
  14.                 android:paddingBottom="10dip"  
  15.                 android:paddingTop="20dip"  
  16.                 android:text="Welcome to Universal Image Loader...."  
  17.                 android:textSize="24sp" />  
  18.    
  19.         <Button  
  20.                 android:layout_width="fill_parent"  
  21.                 android:layout_height="wrap_content"  
  22.                 android:layout_margin="10dip"  
  23.                 android:onClick="listFunc"  
  24.                 android:text="Click here" />  
  25.     </LinearLayout>  
  26.  </ScrollView>  
Step 4
 
Create a layout for displaying the list of images in a list view. Right-click on layout then select "New" -> "Other" -> "Android" -> "Android Layout XML file". Name this file as "image_listview_layout" and add the following code to it:
  1. <ListView xmlns:android="http://schemas.android.com/apk/res/android"  
  2.           android:id="@android:id/list"  
  3.           android:layout_width="fill_parent"  
  4.           android:layout_height="fill_parent" />  
Step 5
 
Right-click on layout then select "New" -> "Other" -> "Android" -> "Android Layout XML file". Name this file as "image_list_layout" and add the following code to it:
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.               android:layout_width="fill_parent"  
  3.               android:layout_height="wrap_content" >  
  4.   <ImageView  
  5.           android:id="@+id/image"  
  6.           android:layout_width="85dip"  
  7.           android:layout_height="80dip"  
  8.           android:layout_margin="3dip"  
  9.           android:adjustViewBounds="true"  
  10.           android:scaleType="centerCrop" />  
  11.   <TextView  
  12.           android:id="@+id/text"  
  13.           android:layout_width="fill_parent"  
  14.           android:layout_height="wrap_content"  
  15.           android:layout_gravity="left|center_vertical"  
  16.           android:layout_marginLeft="20dip"  
  17.           android:textSize="22sp" />  
  18. </LinearLayout>  
Step 6
 
For providing a larger view on the image when the user selects that image from the list.
 
Right-click on layout then select "New" -> "Other" -> "Android" -> "Android Layout XML file". Name this file as "view_layout" and add the following code to it:
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="match_parent"  
  3.     android:layout_height="match_parent"  
  4.     android:orientation="vertical" >  
  5.   <ImageView  
  6.       android:layout_width="300dp"  
  7.       android:layout_height="300dp"  
  8.       android:id="@+id/imFinal"  
  9.       android:layout_marginLeft="20dp"  
  10.       android:layout_marginRight="20dp"  
  11.       android:layout_marginTop="40dp"/>  
  12. </LinearLayout>  
Step 7
 
Open "MainActivity" and add the following code to it:
  1. package com.chhavi.universalimageloader;  
  2.    
  3. import android.app.Activity;  
  4. import android.content.Intent;  
  5. import android.os.Bundle;  
  6. import android.view.Menu;  
  7. import android.view.View;  
  8.    
  9. public class MainActivity extends Activity {  
  10.    
  11.     @Override  
  12.     protected void onCreate(Bundle savedInstanceState) {  
  13.         super.onCreate(savedInstanceState);  
  14.         setContentView(R.layout.activity_main);  
  15.     }  
  16.    
  17.     @Override  
  18.     public boolean onCreateOptionsMenu(Menu menu) {  
  19.         // Inflate the menu; this adds items to the action bar if it is present.  
  20.         getMenuInflater().inflate(R.menu.main, menu);  
  21.         return true;  
  22.     }  
  23.    
  24.     public void listFunc(View view) {  
  25.         Intent i = new Intent(this, ListOfImages.class);  
  26.         startActivity(i);  
  27.     }  
  28. }  
Step 8
 
The following is for displaying the image list.
 
Right-click on your package name then select "New" -> "Class". Name it "ListOfImages" and add the following code to it:
  1. package com.chhavi.universalimageloader;  
  2.    
  3. import java.util.Collections;  
  4. import java.util.LinkedList;  
  5. import java.util.List;  
  6. import android.app.Activity;  
  7. import android.content.Context;  
  8. import android.content.Intent;  
  9. import android.os.Bundle;  
  10. import android.view.View;  
  11. import android.view.ViewGroup;  
  12. import android.widget.AbsListView;  
  13. import android.widget.AdapterView;  
  14. import android.widget.BaseAdapter;  
  15. import android.widget.ImageView;  
  16. import android.widget.ListView;  
  17. import android.widget.TextView;  
  18. import com.nostra13.universalimageloader.core.DisplayImageOptions;  
  19. import com.nostra13.universalimageloader.core.ImageLoader;  
  20. import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;  
  21. import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;  
  22. import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;  
  23.    
  24. public class ListOfImages extends Activity {  
  25.         protected AbsListView list;  
  26.         protected ImageLoader loader = ImageLoader.getInstance();  
  27.    
  28.        final Context context=this;  
  29.     DisplayImageOptions op;  
  30.     String [] images={"http://t2.gstatic.com/images?q=tbn:ANd9GcSZrajzoEXNlRWjMGE9L3kqI1EsFN9P5HCNhMo4xaqLkWuhAixo","http://t0.gstatic.com/images?q=tbn:ANd9GcQH7hisM_szjOKlVdQvq6m_J4lETkWxQOlAk3SMWs051TFFnmWMCA","http://3.bp.blogspot.com/-kAhN0HX-MBk/T_5bApfhbJI/AAAAAAAAAuI/lUww8xT9yV8/s1600/smileys_001_01.png"};   
  31.     @Override  
  32.     public void onCreate(Bundle savedInstanceState) {  
  33.         super.onCreate(savedInstanceState);  
  34.         setContentView(R.layout.image_listview_layout);  
  35.    
  36.         op = new DisplayImageOptions.Builder()  
  37.                 .showStubImage(R.drawable.ic_stub)  
  38.                 .showImageForEmptyUri(R.drawable.ic_empty)  
  39. //                .showImageOnFail(R.drawable.ic_error)  
  40.                 .cacheInMemory()  
  41.                 .cacheOnDisc()  
  42.                 .displayer(new RoundedBitmapDisplayer(20))  
  43.                 .build();  
  44.    
  45.         list = (ListView) findViewById(android.R.id.list);  
  46.         ((ListView) list).setAdapter(new ItemAdapter());  
  47.         list.setOnItemClickListener(new AdapterView.OnItemClickListener() {  
  48.             @Override  
  49.             public void onItemClick(AdapterView<?> parent, View view, int position, long id) {  
  50.                 //tartImagePagerActivity(position);  
  51.    
  52.               Intent i=new Intent(context,SeperateView.class);  
  53.               i.putExtra("pos",position+"");  
  54.               startActivity(i);  
  55.             }  
  56.         });  
  57.     }  
  58.    
  59.     @Override  
  60.     public void onBackPressed() {  
  61.           super.onBackPressed();  
  62.     }  
  63.    
  64.     class ItemAdapter extends BaseAdapter {  
  65.    
  66.         private class ViewHolder {  
  67.             public TextView text;  
  68.             public ImageView image;  
  69.         }  
  70.    
  71.         @Override  
  72.         public int getCount() {  
  73.             return images.length;  
  74.         }  
  75.    
  76.         @Override  
  77.         public Object getItem(int position) {  
  78.             return position;  
  79.         }  
  80.    
  81.         @Override  
  82.         public long getItemId(int position) {  
  83.             return position;  
  84.         }  
  85.    
  86.         @Override  
  87.         public View getView(final int position, View convertView, ViewGroup parent) {  
  88.             View v = convertView;  
  89.             final ViewHolder holder;  
  90.             if (convertView == null) {  
  91.                 v = getLayoutInflater().inflate(R.layout.image_list_layout, parent, false);  
  92.                 holder = new ViewHolder();  
  93.                 holder.text = (TextView) v.findViewById(R.id.text);  
  94.                 holder.image = (ImageView) v.findViewById(R.id.image);  
  95.                 v.setTag(holder);  
  96.             } else {  
  97.                 holder = (ViewHolder) v.getTag();  
  98.             }  
  99.    
  100.             holder.text.setText("Item " + (position + 1));  
  101.             loader.displayImage(images[position], holder.image, op, null);  
  102.    
  103.             return v;  
  104.         }  
  105.     }  
  106.  }  
"images" is a string array that contains the list of image URL's. First, we have set the initial configurations of the image. "stub_image" is the image that will be displayed until the image from the URL is not loaded. In "getView()" we have set the content of the list view. You will need to paste the images that you want to use as a stub_image and the image used in "showImageForEmptyUri()" in your drawable folder.
 
Step 9
 
Create a class to provide a larger view of the image when selected by the user from the list.
 
Right-click on your package name then select "New" -> "Class". Name it "SeperateView" and add the following code to it:
  1. package com.chhavi.universalimageloader;  
  2.    
  3. import android.app.Activity;  
  4. import android.content.Intent;  
  5. import android.os.Bundle;  
  6. import android.widget.ImageView;  
  7. import com.nostra13.universalimageloader.core.DisplayImageOptions;  
  8. import com.nostra13.universalimageloader.core.ImageLoader;  
  9. import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;  
  10.    
  11. public class SeperateView extends Activity {  
  12.    
  13.         DisplayImageOptions options;  
  14.         String [] imageUrls={"http://t2.gstatic.com/images?q=tbn:ANd9GcSZrajzoEXNlRWjMGE9L3kqI1EsFN9P5HCNhMo4xaqLkWuhAixo","http://t0.gstatic.com/images?q=tbn:ANd9GcQH7hisM_szjOKlVdQvq6m_J4lETkWxQOlAk3SMWs051TFFnmWMCA","http://3.bp.blogspot.com/-kAhN0HX-MBk/T_5bApfhbJI/AAAAAAAAAuI/lUww8xT9yV8/s1600/smileys_001_01.png"};   
  15.         protected ImageLoader imageLoader = ImageLoader.getInstance();  
  16.    
  17.        protected void onCreate(Bundle savedInstanceState) {  
  18.        super.onCreate(savedInstanceState);  
  19.     setContentView(R.layout.view_layout);  
  20.    
  21.     ImageView im=(ImageView)findViewById(R.id.imFinal);  
  22.    
  23.     options = new DisplayImageOptions.Builder()  
  24.             .showStubImage(R.drawable.ic_stub)  
  25.             .showImageForEmptyUri(R.drawable.ic_empty)  
  26.             //.showImageOnFail(R.drawable.ic_error)  
  27.             .cacheInMemory()  
  28.             .cacheOnDisc()  
  29.             .displayer(new RoundedBitmapDisplayer(20))  
  30.             .build();  
  31.     Intent i=getIntent();  
  32.     int pos=Integer.parseInt(i.getStringExtra("pos"));  
  33.     imageLoader.displayImage(imageUrls[pos], im, options, null);  
  34.    
  35.     }  
Step 10
 
Open "AndroidManifest" and apply the following changes:
  1. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     package="com.chhavi.universalimageloader"  
  3.     android:versionCode="1"  
  4.     android:versionName="1.0" >  
  5.    
  6.   <uses-permission android:name="android.permission.INTERNET" />  
  7.    
  8.   <uses-sdk  
  9.       android:minSdkVersion="8"  
  10.       android:targetSdkVersion="17" />  
  11.    
  12.   <application  
  13.       android:name="com.chhavi.universalimageloader.App"  
  14.       android:allowBackup="true"  
  15.       android:icon="@drawable/ic_launcher"  
  16.       android:label="@string/app_name"  
  17.       android:theme="@style/AppTheme" >  
  18.     <activity  
  19.         android:name="com.chhavi.universalimageloader.MainActivity"  
  20.         android:label="@string/app_name" >  
  21.       <intent-filter>  
  22.         <action android:name="android.intent.action.MAIN" />  
  23.    
  24.         <category android:name="android.intent.category.LAUNCHER" />  
  25.       </intent-filter>  
  26.     </activity>  
  27.     <activity  
  28.         android:name="com.chhavi.universalimageloader.ListOfImages"  
  29.         android:label="Image list" />  
  30.     <activity  
  31.         android:name="com.chhavi.universalimageloader.SeperateView"  
  32.         android:label="View Image" />     
  33.   </application>  
  34. </manifest> 
Output snapshots:
 
im1.jpg
 
On button click:
 
im2.jpg
 
Note you will see the stub_image until a URL image is loaded.
 
Clicking Item 1:
 
im3.jpg
 
Clicking Item 2:
 
im4.jpg
 
Clicking Item 5:
 
im5.jpg
 
Thank you..... Enjoy coding :) 


Similar Articles