Android Universal Image Loader From Url

android universal image loader

Applications depend on good user interface to attract the biggest number of users, and displaying images in your app sure will help in the process, but adding too much images to your app will result in a big .apk file size, which is a bad thing, so the solution is to put just the major images in your .apk file and the rest will be downloaded from the internet once the user starts the app. How to do so? Using the Android Universal Image Loader library, the process is very easy and efficient.

Android Universal Image Loader library will allow you to:

  1. Download image from a specific url
  2. Multi thread image loading (async or sync)
  3. Display the downloaded image in an image view
  4. Save the image in internal storage cache
  5. Save the image in external storage cache
  6. Display a loading image while download the targeted image
  7. Display an error image when connection is lost or image is not found
  8. If the image is found in cache it will be displayed immediately
  9. Many customization options for every display image call (stub images, caching switch, decoding options, Bitmap processing and displaying, etc.)
  10. Listening loading process (including downloading progress)

Android 2.0+ support

Let’s start:

1- Include the library in your project:

You can choose one of theses 3 ways:

1- Manual:

Download The JAR File  and put it in the libs subfolder of your Android project and sync your project

2- Gradle dependency:

Add this to your build.gradle file:

compile 'com.nostra13.universalimageloader:universal-image-loader:1.9.5'

3- Maven dependency:

<dependency>
    <groupId>com.nostra13.universalimageloader</groupId>
    <artifactId>universal-image-loader</artifactId>
    <version>1.9.5</version>
</dependency>


2- Add App permissions:

Add the following code to your Manifest.xml file

<manifest>
    <!-- Include following permission if you load images from Internet -->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- Include following permission if you want to cache images on SD card -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    ...
</manifest>

3- Setup the Library Class Before Usage:

You can setup the imageLoader class either in your current activity or in an application class (Recommended), to do so add the below code

 // Create global configuration and initialize ImageLoader with this config
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
            ...
            .build();
        ImageLoader.getInstance().init(config);

4- Setup the ImageLoader Configuration:

ImageLoader Configuration (ImageLoaderConfiguration) is global for application. You should set it once.

All options in Configuration builder are optional. Use only those you really want to customize.
See default values for config options in Java docs for every option.

This is an example of all options found, choose what best meets your needs

// DON'T COPY THIS CODE TO YOUR PROJECT! This is just example of ALL options using.
// See the sample project how to use ImageLoader correctly.
File cacheDir = StorageUtils.getCacheDirectory(context);
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
        .memoryCacheExtraOptions(480, 800) // default = device screen dimensions
        .diskCacheExtraOptions(480, 800, null)
        .taskExecutor(...)
        .taskExecutorForCachedImages(...)
        .threadPoolSize(3) // default
        .threadPriority(Thread.NORM_PRIORITY - 2) // default
        .tasksProcessingOrder(QueueProcessingType.FIFO) // default
        .denyCacheImageMultipleSizesInMemory()
        .memoryCache(new LruMemoryCache(2 * 1024 * 1024))
        .memoryCacheSize(2 * 1024 * 1024)
        .memoryCacheSizePercentage(13) // default
        .diskCache(new UnlimitedDiskCache(cacheDir)) // default
        .diskCacheSize(50 * 1024 * 1024)
        .diskCacheFileCount(100)
        .diskCacheFileNameGenerator(new HashCodeFileNameGenerator()) // default
        .imageDownloader(new BaseImageDownloader(context)) // default
        .imageDecoder(new BaseImageDecoder()) // default
        .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
        .writeDebugLogs()
        .build();

5- Setup the Display Options:




Display Options (DisplayImageOptions) are local for every display task (ImageLoader.displayImage(…)).

Display Options can be applied to every display task (ImageLoader.displayImage(…) call).

Note: If Display Options wasn’t passed to ImageLoader.displayImage(…) method then default Display Options from configuration (ImageLoaderConfiguration.defaultDisplayImageOptions(…)) will be used.

// DON'T COPY THIS CODE TO YOUR PROJECT! This is just example of ALL options using.
// See the sample project how to use ImageLoader correctly.
DisplayImageOptions options = new DisplayImageOptions.Builder()
        .showImageOnLoading(R.drawable.ic_stub) // resource or drawable
        .showImageForEmptyUri(R.drawable.ic_empty) // resource or drawable
        .showImageOnFail(R.drawable.ic_error) // resource or drawable
        .resetViewBeforeLoading(false)  // default
        .delayBeforeLoading(1000)
        .cacheInMemory(false) // default
        .cacheOnDisk(false) // default
        .preProcessor(...)
        .postProcessor(...)
        .extraForDownloader(...)
        .considerExifParams(false) // default
        .imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2) // default
        .bitmapConfig(Bitmap.Config.ARGB_8888) // default
        .decodingOptions(...)
        .displayer(new SimpleBitmapDisplayer()) // default
        .handler(new Handler()) // default
        .build();

6- Using the Library:

To start using the library declare the imageLoader class

ImageLoader imageLoader = ImageLoader.getInstance(); // Get singleton instance

then load the image in the targeted imageView:

// Load image, decode it to Bitmap and display Bitmap in ImageView (or any other view 
//  which implements ImageAware interface)
imageLoader.displayImage(imageUri, imageView);

You can just load the image and not display it directly in an imageView for later usage using the loadImage function:

// Load image, decode it to Bitmap and return Bitmap to callback
imageLoader.loadImage(imageUri, new SimpleImageLoadingListener() {
    @Override
    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
        // Do whatever you want with Bitmap
    }
});


// Load image, decode it to Bitmap and return Bitmap synchronously
Bitmap bmp = imageLoader.loadImageSync(imageUri);

The displayImage function contain many inner useful functions that can be used here is a complete example:

// Load image, decode it to Bitmap and display Bitmap in ImageView (or any other view 
//  which implements ImageAware interface)
imageLoader.displayImage(imageUri, imageView, options, new ImageLoadingListener() {
    @Override
    public void onLoadingStarted(String imageUri, View view) {
        ...
    }
    @Override
    public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
        ...
    }
    @Override
    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
        ...
    }
    @Override
    public void onLoadingCancelled(String imageUri, View view) {
        ...
    }
}, new ImageLoadingProgressListener() {
    @Override
    public void onProgressUpdate(String imageUri, View view, int current, int total) {
        ...
    }
});
// Load image, decode it to Bitmap and return Bitmap to callback
ImageSize targetSize = new ImageSize(80, 50); // result Bitmap will be fit to this size
imageLoader.loadImage(imageUri, targetSize, options, new SimpleImageLoadingListener() {
    @Override
    public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
        // Do whatever you want with Bitmap
    }
});
// Load image, decode it to Bitmap and return Bitmap synchronously
ImageSize targetSize = new ImageSize(80, 50); // result Bitmap will be fit to this size
Bitmap bmp = imageLoader.loadImageSync(imageUri, targetSize, options);

And that’s it you are all setup. 😀

7- Acceptable URIs examples:

"http://site.com/image.png" // from Web
"file:///mnt/sdcard/image.png" // from SD card
"file:///mnt/sdcard/video.mp4" // from SD card (video thumbnail)
"content://media/external/images/media/13" // from content provider
"content://media/external/video/media/13" // from content provider (video thumbnail)
"assets://image.png" // from assets
"drawable://" + R.drawable.img // from drawables (non-9patch images)

NOTE: Use drawable:// only if you really need it! Always consider the native way to load drawables – ImageView.setImageResource(…) instead of using of ImageLoader.

 

License

Copyright 2011-2015 Sergey Tarasevich

Licensed under the Apache License, Version 2.0 (the “License”);
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an “AS IS” BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Source: Github Universal Image Loader