How To Use universal image loader offline caching?
Asked Answered
D

5

14

Is it possible to catch offline using universal image loader? If possible, how to use it? Using configs? How To Set Download Directory manually?

out of memory erroron load huge images :

my codes :

DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
            .cacheOnDisc(true).cacheInMemory(true)
            .imageScaleType(ImageScaleType.IN_SAMPLE_INT)
            .displayer(new FadeInBitmapDisplayer(300)).build();
    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(G.appConfigs.context)
            .defaultDisplayImageOptions(defaultOptions)
            .memoryCacheExtraOptions(480, 800) // default = device screen dimensions
            .diskCacheExtraOptions(480, 800, null)
            .memoryCache(new WeakMemoryCache())
            .memoryCache(new LruMemoryCache(2 * 1024 * 1024))
            .memoryCacheSize(2 * 1024 * 1024)
            .discCacheSize(300 * 1024 * 1024)
            .build();
    ImageLoader.getInstance().init(config);
    // END - UNIVERSAL IMAGE LOADER SETUP

    ImageLoader imageLoader = ImageLoader.getInstance();

        DisplayImageOptions options = new DisplayImageOptions.Builder().cacheInMemory(true)
            .cacheOnDisc(true).resetViewBeforeLoading(true)
            .showImageForEmptyUri(R.drawable.no_pic)
            .showImageOnFail(R.drawable.load_failed)
            .showImageOnLoading(R.drawable.img_thumb).build();

    //download and display image from url
    imageLoader.displayImage(imgURL, img, options);

how to resolve it ?

Deformed answered 22/9, 2014 at 6:59 Comment(0)
Y
15

You can use the ImageLoaderConfiguration.Builder class to customize disk caching. This includes the methods:

  • diskCacheExtraOptions()
  • diskCacheSize() (in bytes).
  • diskCacheFileCount()
  • diskCacheFileNameGenerator()
  • and some others.

Or you can just use diskCache(DiskCache) to provide a custom class for implementing offline caching.

From the example in the Configuration section of the wiki:

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 - 1) // default
    .tasksProcessingOrder(QueueProcessingType.FIFO) // default
    .denyCacheImageMultipleSizesInMemory()
    .memoryCache(new LruMemoryCache(2 * 1024 * 1024))
    .memoryCacheSize(2 * 1024 * 1024)
    .memoryCacheSizePercentage(13) // default
    .diskCache(new UnlimitedDiscCache(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();
Yvor answered 9/11, 2014 at 18:26 Comment(4)
So It Shows Images OffLine ? Thank You So MuchDeformed
If I close the app and then restart it, would it still keep the cached images? Is their a way to persist them using universal image loader?Desegregate
@ShobhitPuri That's the purpose of this feature.Yvor
how i can reach image local path ?Deformed
M
4

But if you restart your device or clean your cache by anyway it will not work offline as the cached files will be deleted.
To Show offline images you have to download images on sd-card to a specific folder and have to pick from there in case on offline.

Mindymine answered 13/11, 2014 at 12:56 Comment(2)
You mean to say that if one follows procedure mentioned by @matiash, the images will be deleted on restart. Aah! Didn't know that.Desegregate
So that means Universal Image Loader cannot be used for offline storing the images. Do you know any library which would simplify this. Other wise I would have to use AsyncTask and download images from all URL's and either store it in database or somewhere on the SD card. I thought a library would make this easier.Desegregate
M
3

Don't Know much about such lib. but you can use the following method to download your images. Just Call it from an Async. Task and pass your url.

private File root = Environment.getExternalStorageDirectory();
private File dir = new File(root.getAbsolutePath() + "/ImageFolder");

private void downloadFile(String url) throws Exception {
    URL ur = new URL(url);
    String fileName = url.substring(url.lastIndexOf("/") + 1);
    File file = new File(dir, fileName);
    URLConnection uconn = ur.openConnection();
    InputStream is = uconn.getInputStream();
    BufferedInputStream bufferinstream = new BufferedInputStream(is);
    ByteArrayBuffer baf = new ByteArrayBuffer(5000);
    int current = 0;
    while ((current = bufferinstream.read()) != -1) {
        baf.append((byte) current);
    }
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(baf.toByteArray());
    fos.flush();
    fos.close();
}
Mindymine answered 14/11, 2014 at 8:51 Comment(2)
i want to use it at listview or gridview , i know about download methods and i did it before but i want to use easiest way to resolve it.Deformed
you need a permanent cache (offline support).? or just want to do a lazy loading.?Mindymine
A
1

Universal Image Loader is one perfect library to load async your images. You can use @matiash answer to setup library configuration and then with

ImageLoader.getInstance().init(config);

you can apply them to the ImageLoader instance. After that if you have internet connection at the begin of your application, Universal Image Loader will download and cache all your images, on the places where you use loading of those images with Universal Image Loader library. The next time when you load same images, Universal Image Loader will get them from the cache, which means you don't need to have any internet connection(can work offline). The problem came when somebody is installing your application and trying to start using it for the first time, and if he doesn't have internet connection. Then Universal Image Loader will try to load your images from the web server and cache them to the storage, but it will fail because you don't have internet connection. That's why Universal Image Loader has a class like DisplayImageOptions :

new DisplayImageOptions.Builder()

which allow you to setup what should happen when there is a problem with loading your images. You can use for this purpose methods like:

.showImageOnLoading(R.drawable.default_image)
.showImageForEmptyUri(R.drawable.default_image)
.showImageOnFail(R.drawable.default_image)

Here is an example how you can use it:

DisplayImageOptions imageOptions = new DisplayImageOptions.Builder()
    .showImageOnLoading(getImageLoaderDefaultImage())
    .showImageForEmptyUri(getImageLoaderDefaultImage())
    .showImageOnFail(getImageLoaderDefaultImage())
    .cacheInMemory(true)
    .cacheOnDisk(true)
    .considerExifParams(true)
    .build();

Method getImageLoaderDefaultImage():

private int getImageLoaderDefaultImage(){ return R.drawable.default_img;}

And here is how to use Image Loader when you want to load image:

ImageLoader.getInstance().displayImage("image url", myImageView,imageOptions);
Achondroplasia answered 7/7, 2015 at 6:43 Comment(0)
S
0

If you are using Xamarin : Add Below code in OnCreateView or similar is available in Java also.

DisplayImageOptions options = new DisplayImageOptions.Builder().CacheInMemory(true).CacheOnDisk(true).Build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this.Context).DefaultDisplayImageOptions(options).Build();
ImageLoader.Instance.Init(config);

Add below line of code, when loading image

ImageLoader imageLoader = ImageLoader.Instance;
imageLoader.DisplayImage(imgURL, imageSource);
Spinule answered 8/1, 2017 at 6:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.