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:

package com.chhavi.universalimageloader;

 

import android.app.Application;

import android.content.Context;

import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;

import com.nostra13.universalimageloader.core.ImageLoader;

import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

 

public class App extends Application {

    @Override

    public void onCreate() {

 

        super.onCreate();

        initImageLoader(getApplicationContext());

    }

 

    public static void initImageLoader(Context context) {

      

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)

                .threadPriority(Thread.NORM_PRIORITY - 2)

                .denyCacheImageMultipleSizesInMemory()

                .discCacheFileNameGenerator(new Md5FileNameGenerator())

                .tasksProcessingOrder(QueueProcessingType.LIFO)

                .enableLogging()

                .build();

 

        ImageLoader.getInstance().init(config);

    }

}

 

Step 3:

Open the "activity_main" layout file and add the following code to it:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"

            android:layout_width="fill_parent"

            android:layout_height="fill_parent" >

 

    <LinearLayout

            android:layout_width="fill_parent"

            android:layout_height="fill_parent"

            android:orientation="vertical" >

 

        <TextView

                android:layout_width="fill_parent"

                android:layout_height="wrap_content"

                android:gravity="center"

                android:paddingBottom="10dip"

                android:paddingTop="20dip"

                android:text="Welcome to Universal Image Loader...."

                android:textSize="24sp" />

 

        <Button

                android:layout_width="fill_parent"

                android:layout_height="wrap_content"

                android:layout_margin="10dip"

                android:onClick="listFunc"

                android:text="Click here" />

    </LinearLayout>

 </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:

<ListView xmlns:android="http://schemas.android.com/apk/res/android"

          android:id="@android:id/list"

          android:layout_width="fill_parent"

          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:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

              android:layout_width="fill_parent"

              android:layout_height="wrap_content" >

  <ImageView

          android:id="@+id/image"

          android:layout_width="85dip"

          android:layout_height="80dip"

          android:layout_margin="3dip"

          android:adjustViewBounds="true"

          android:scaleType="centerCrop" />

  <TextView

          android:id="@+id/text"

          android:layout_width="fill_parent"

          android:layout_height="wrap_content"

          android:layout_gravity="left|center_vertical"

          android:layout_marginLeft="20dip"

          android:textSize="22sp" />

</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:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:orientation="vertical" >

  <ImageView

      android:layout_width="300dp"

      android:layout_height="300dp"

      android:id="@+id/imFinal"

      android:layout_marginLeft="20dp"

      android:layout_marginRight="20dp"

      android:layout_marginTop="40dp"/>

</LinearLayout> 

Step 7:

Open "MainActivity" and add the following code to it:

package com.chhavi.universalimageloader;

 

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.view.Menu;

import android.view.View;

 

public class MainActivity extends Activity {

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

    }

 

    @Override

    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.

        getMenuInflater().inflate(R.menu.main, menu);

        return true;

    }

 

    public void listFunc(View view) {

        Intent i = new Intent(this, ListOfImages.class);

        startActivity(i);

    }

} 

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:

package com.chhavi.universalimageloader;

 

import java.util.Collections;

import java.util.LinkedList;

import java.util.List;

import android.app.Activity;

import android.content.Context;

import android.content.Intent;

import android.os.Bundle;

import android.view.View;

import android.view.ViewGroup;

import android.widget.AbsListView;

import android.widget.AdapterView;

import android.widget.BaseAdapter;

import android.widget.ImageView;

import android.widget.ListView;

import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;

import com.nostra13.universalimageloader.core.ImageLoader;

import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;

import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener;

import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

 

public class ListOfImages extends Activity {

        protected AbsListView list;

        protected ImageLoader loader = ImageLoader.getInstance();

 

       final Context context=this;

    DisplayImageOptions op;

    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"}; 

    @Override

    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.image_listview_layout);

 

        op = new DisplayImageOptions.Builder()

                .showStubImage(R.drawable.ic_stub)

                .showImageForEmptyUri(R.drawable.ic_empty)

//                .showImageOnFail(R.drawable.ic_error)

                .cacheInMemory()

                .cacheOnDisc()

                .displayer(new RoundedBitmapDisplayer(20))

                .build();

 

        list = (ListView) findViewById(android.R.id.list);

        ((ListView) list).setAdapter(new ItemAdapter());

        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override

            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                //tartImagePagerActivity(position);

 

              Intent i=new Intent(context,SeperateView.class);

              i.putExtra("pos",position+"");

              startActivity(i);

            }

        });

    }

 

    @Override

    public void onBackPressed() {

          super.onBackPressed();

    }

 

    class ItemAdapter extends BaseAdapter {

 

        private class ViewHolder {

            public TextView text;

            public ImageView image;

        }

 

        @Override

        public int getCount() {

            return images.length;

        }

 

        @Override

        public Object getItem(int position) {

            return position;

        }

 

        @Override

        public long getItemId(int position) {

            return position;

        }

 

        @Override

        public View getView(final int position, View convertView, ViewGroup parent) {

            View v = convertView;

            final ViewHolder holder;

            if (convertView == null) {

                v = getLayoutInflater().inflate(R.layout.image_list_layout, parent, false);

                holder = new ViewHolder();

                holder.text = (TextView) v.findViewById(R.id.text);

                holder.image = (ImageView) v.findViewById(R.id.image);

                v.setTag(holder);

            } else {

                holder = (ViewHolder) v.getTag();

            }

 

            holder.text.setText("Item " + (position + 1));

            loader.displayImage(images[position], holder.image, op, null);

 

            return v;

        }

    }

    } 

"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 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 to 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:

package com.chhavi.universalimageloader;

 

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.widget.ImageView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;

import com.nostra13.universalimageloader.core.ImageLoader;

import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

 

public class SeperateView extends Activity {

 

        DisplayImageOptions options;

        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"}; 

        protected ImageLoader imageLoader = ImageLoader.getInstance();

 

       protected void onCreate(Bundle savedInstanceState) {

       super.onCreate(savedInstanceState);

    setContentView(R.layout.view_layout);

 

    ImageView im=(ImageView)findViewById(R.id.imFinal);

 

    options = new DisplayImageOptions.Builder()

            .showStubImage(R.drawable.ic_stub)

            .showImageForEmptyUri(R.drawable.ic_empty)

            //.showImageOnFail(R.drawable.ic_error)

            .cacheInMemory()

            .cacheOnDisc()

            .displayer(new RoundedBitmapDisplayer(20))

            .build();

    Intent i=getIntent();

    int pos=Integer.parseInt(i.getStringExtra("pos"));

    imageLoader.displayImage(imageUrls[pos], im, options, null);

 

}

}


Step 10:

Open "AndroidManifest" and apply the following changes:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.chhavi.universalimageloader"

    android:versionCode="1"

    android:versionName="1.0" >

 

  <uses-permission android:name="android.permission.INTERNET" />

 

  <uses-sdk

      android:minSdkVersion="8"

      android:targetSdkVersion="17" />

 

  <application

      android:name="com.chhavi.universalimageloader.App"

      android:allowBackup="true"

      android:icon="@drawable/ic_launcher"

      android:label="@string/app_name"

      android:theme="@style/AppTheme" >

    <activity

        android:name="com.chhavi.universalimageloader.MainActivity"

        android:label="@string/app_name" >

      <intent-filter>

        <action android:name="android.intent.action.MAIN" />

 

        <category android:name="android.intent.category.LAUNCHER" />

      </intent-filter>

    </activity>

    <activity

        android:name="com.chhavi.universalimageloader.ListOfImages"

        android:label="Image list" />

    <activity

        android:name="com.chhavi.universalimageloader.SeperateView"

        android:label="View Image" />   

  </application>

</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 :) 

Up Next
    Ebook Download
    View all
    Learn
    View all