When using images for an android application. You often encounter a situation where you need to display an image located in a remote server. Since displaying images directly on the views would have considerable impact on the application, we need to cache them first before displaying them. To assist me in this scenarios, I use the
Universal Image Loader.
To start using this library, you need to include the
universal-image-loader-x.y.z.jar file into your project.
Set the permissions on the application manifest:
1: <uses-permission android:name="android.permission.INTERNET" />
2: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Create a subclass of the
Application class where you will initialize the image loader configuration:
1: public class UILDemoApplication extends Application {
2: @Override
3: public void onCreate() {
4: super.onCreate();
5: ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
6: .threadPriority(Thread.NORM_PRIORITY - 2)
7: .denyCacheImageMultipleSizesInMemory()
8: .discCacheFileNameGenerator(new Md5FileNameGenerator())
9: .tasksProcessingOrder(QueueProcessingType.LIFO)
10: .enableLogging()
11: .build();
12: ImageLoader.getInstance().init(config);
13: }
14: }
Update your application manifest to set the name of the Application tag into UILDemoApplication the class name:
1: <application
2: android:name=".UILDemoApplication"
3: android:allowBackup="true"
4: android:icon="@drawable/ic_launcher"
5: android:label="@string/app_name"
6: android:theme="@style/AppTheme" >
To use the image loader, first get an instance to the image loader class. In my sample application, it is located on the ImageListAdapter that I created:
1: private Context context;
2: private ImageLoader imageLoader;
3: public ImageListAdapter(Context context) {
4: this.context = context;
5: imageLoader = ImageLoader.getInstance();
6: }
For loading images on your image view, you can use check on the sample code below
1: DisplayImageOptions options = new DisplayImageOptions.Builder()
2: .cacheOnDisc()
3: .build();
4: imageLoader.displayImage(urls[position], vh.imageView, options);
As you can see from the code above, I specified some options for displaying the image. I enabled caching the image on the disc so that we won't need to download the image everytime we need to display it. It is also possible to display the image without any options by just calling:
1: imageLoader.displayImage(urls[position], vh.imageView);
The full source code for this tutorial can be found
here.