/ImageLoader

Library for async image loading and caching on Android

Primary LanguageJavaOtherNOASSERTION

ImageLoader

ImageLoader is a simple library that makes it easy to download, display and cache remote images in Android apps.
Image download happens off the UI thread and the images are cached with a two-level in-memory/SD card cache.

Recent changes

1.5.8-SNAPSHOT

  • Added the possibility of loading a picture with an Animation

1.5.7

  • ImageTagFactory has now factory methods for writing better tests.
    When upgrading, please use ImageTagFactory.getInstance instead of new ImageFactory()
  • Added callback when image is loaded, more methods on SettingsBuilder
  • Added ability to disable bitmap resizing
  • Fixed some problems scrolling through long lists
  • Added an error image when the URL is null
  • Fix for loading images behind redirects (max 3)

1.5.6

  • Removed necessity to set a service in the manifest for the clean up. Everything is done in the BasicFileManager with a background thread.

1.5.5

  • Bug fixes
  • New DirectLoader utility to directly download images (do not use on main thread)

1.5.2

  • Added support to load a cached small image as the preview for a larger image

1.5.1

  • Improved concurrent loader
  • Change SD card cache directory to respect Android SDK guidelines
  • Improved LruBitmapCache

Using the library

The demo project is a good place to start. Check the TODO comments to see where the important stuff happens.

If that sounds like too much trouble, here are the steps:

Overview

General overview

In the Application class

Add the following code to initialise and provide access to the image loader. The settings builder gives you some control over the caching and network connections.

@Override
public void onCreate() {
    super.onCreate();
    LoaderSettings settings = new SettingsBuilder()
      .withDisconnectOnEveryCall(true).build(this);
    imageManager = new ImageManager(this, settings);
}

public static final ImageManager getImageManager() {
    return imageManager;
}
LRU cache option

The default cache uses soft references. With a memory-constrained system like Android, space can be reclaimed too often, limiting the performance of the cache. The LRU cache is intended to solve this problem. It’s particularly useful if your app displays many small images.

settings = new SettingsBuilder()
  .withCacheManager(new LruBitmapCache(this)).build(this);
thumbnailImageLoader = new ImageManager(this, settings);

The LruBitmapCache will take 25% of the free memory available for the cache by default. You can customise this with an alternative constructor:

int PERCENTAGE_OF_CACHE = 50;
settings = new SettingsBuilder()
  .withCacheManager(new LruBitmapCache(this, PERCENTAGE_OF_CACHE)).build(this);
thumbnailImageLoader = new ImageManager(this, settings);
Additional settings

ImageLoader uses UrlConnection to fetch images. There are two important UrlConnection parameters that you might want to change: connectionTimeout & readTimeout.

SettingsBuilder builder = new SettingsBuilder();
Settings settings = builder.withConnectionTimeout(20000)
  .withReadTimeout(30000).build(this);

The connection timeout is the timeout for the initial connection. The read timeout is the timeout waiting for data.

In the Activity, Fragment or Adapter

When you want to load an image into an ImageView, you just get the image loader from the Application class and call the load method.
Here is how you could use it in a ListView with the binder setting the image URL in the ImageView as a tag:

ImageTagFactory imageTagFactory = new ImageTagFactory(this, R.drawable.bg_img_loading);
imageTagFactory.setErrorImageId(R.drawable.bg_img_notfound);

private ViewBinder getViewBinder() {
  return new ViewBinder() {
    @Override
    public boolean setViewValue(View view, Cursor cursor, int columnIndex) {
      // Build image tag with remote image URL
      ImageTag tag = imageTagFactory.build(cursor.getString(columnIndex));
      ((ImageView) view).setTag(tag);
      imageLoader.load(view);
      return true;
    }
  };
}

The ImageTagFactory configures image loader with the size of the images to display and the loading image to be displayed whilst the real image is being fetched. The image loader will fetch the image from the in-memory cache (if available), from the SD card (if available) or from the network as a last resort.

Cleaning the SD card cache

If you want ImageLoader to clean up the SD card cache, add the following code in the onCreate of the Application class:

imageManager.getFileManager().clean();

In the settings builder you can configure the expiration period (it’s set to 7 days by default).

In the AndroidManifest.xml

There are two things you need to add: Permissions and the Service to clean up the SD cache. (Since 1.5.6 the cleanup service is no longer required!)

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

<service android:name="com.novoda.imageloader.core.service.CacheCleaner" android:exported="true">
  <intent-filter>
    <action android:name="com.novoda.imageloader.core.action.CLEAN_CACHE" />
  </intent-filter>
</service>

Cached preview images (optional)

Cached preview images is a feature designed for when you have a list of items with thumbnail images and you subsequently display a larger version of the same image on some user action. ImageLoader can take the small image from the cache (if available) and use it as the preview image whilst the large image loads.

There are two options for implementing cached preview images: configure the image tag before calling load or configure the ImageTagFactory.

// Image tag after normal settings 
imageTag.setPreviewHeight(100);
imageTag.setPreviewHeight(100);
imageTag.setPreviewUrl(previewUrl);
imageView.setTag(imageTag);
getImageManager().getLoader().load(imageView);
// If small and large image have same URL, configure with the ImageTagFactory
imageTagFactory = new ImageTagFactory(this, R.drawable.loading);
imageTagFactory.setErrorImageId(R.drawable.image_not_found);
imageTagFactory.usePreviewImage(THUMB_IMAGE_SIZE, THUMB_IMAGE_SIZE, true);

// On bind 
ImageView imageView = (ImageView) view;
String url = cursor.getString(columnIndex);
imageView.setTag(imageTagFactory.build(url));
MyApplication.getImageManager().getLoader().load(imageView);

DirectLoader (utility)

ImageLoader contains a utility class for directly downloading a Bitmap from a URL. This is useful for downloading an image to display in a notification. This does NOT handle threading for you. You should do the download inside an AsyncTask or Thread.

Bitmap myImage = new DirectLoader().download(url);

This method will throw an ImageNotFoundException if there is no image on the other end of your URL.

Adding an animation

If you want to load a an image using an animation you just have to add an Animation object to the imageLoader.load method



ImageTagFactory imageTagFactory = new ImageTagFactory(this, R.drawable.bg_img_loading);
imageTagFactory.setErrorImageId(R.drawable.bg_img_notfound);

Animation fadeInAnimation = AnimationUtils.loadAnimation(this, R.anim.fade_in);
imageTagFactory.setAnimation(fadeInAnimation);

Getting the library

Using Maven

If you are using Maven you can define the repo and dependency in your POM:

<dependency>
  <groupId>com.novoda.imageloader</groupId>
  <artifactId>imageloader-core</artifactId>
 <version>1.5.6</version>
</dependency>

As a .jar

You can also simply include the latest version of the .jar file (v 1.5.6) in you project.

Helping out

Novoda <3 open source.

Report issues

If you have a problem with the library or want to suggest new features, let us know by creating an issue in GitHub.

Get involved

If you don’t want to wait for us to fix a bug or implement a new feature, you can contribute to the project. Fork the repo and submit a pull request with your changes. Find out more about pull requests.

Project structure

  • core: simple Maven Java project
  • demo: Android project to test ImageLoader
  • acceptance: Android project for Robotium instrumentation tests

Building the projects with maven

mvn clean install

Note : By default we run instrumentation tests, if you don’t attach a device the build will fail at the end.

Eclipse

Here are some simple steps to set up the project in Eclipse:

  • Run mvn clean install -Peclipse. This command copies the dependencies to libs for working in Eclipse. The demo and acceptance projects should be configured as Android projects.
  • Import the core project as a Maven project
  • Create a new Android project from source and target the demo directory.
  • Create new Android project from source and target the acceptance directory.

IntelliJ

Import as a Maven project from the project root.

Requirements

  • Maven 3.0.3+

License

Copyright © 2012 Novoda Ltd.
Released under the Apache License, Version 2.0