Use two biblotecas in my application, Universal Image Loader and another that uses the library picasso,
the picasso library, records the image in the cache /cache/picasso-cache/ and the names are generated with the MD5 URL.
To separate the cache Universal Image Loader, I write to /cache/LazyLoad/ and names generated with the item ID.
My code of configuration Universal Image Loader
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.resetViewBeforeLoading(true)
.cacheOnDisk(true)
.cacheInMemory(true)
.imageScaleType(ImageScaleType.EXACTLY)
.displayer(new FadeInBitmapDisplayer(300))
.build();
ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(getApplicationContext());
config.defaultDisplayImageOptions(defaultOptions);
config.memoryCache(new WeakMemoryCache());
config.threadPriority(Thread.NORM_PRIORITY - 2);
config.denyCacheImageMultipleSizesInMemory();
config.tasksProcessingOrder(QueueProcessingType.LIFO);
config.writeDebugLogs(); // for debug
FileNameGenerator fileNameGenerator = new FileNameGenerator() {
#Override
public String generate(String imageUri) {
String fileName = imageUri.substring(imageUri.lastIndexOf('/')+1, imageUri.length());
String fileNameWithoutExtension = fileName.substring(0, fileName.lastIndexOf('.'));
return fileNameWithoutExtension;
}
};
String pathCache = Globais.getCacheDirImageLazyLoad(mContext); //returns StorageUtils.getCacheDirectory(context, false).getAbsolutePath() + "/lazyload";
File f = new File(pathCache);
if (!f.exists())
f.mkdirs();
DiskCache diskCache = new UnlimitedDiskCache(f, null, fileNameGenerator);
config.diskCache(diskCache);
config.diskCacheFileNameGenerator(fileNameGenerator);
ImageLoader.getInstance().init(config.build());
Problem that after I started using the component that uses the picasso, began to double the cache, ALL images that use the Universal Image Loader, also appear in Picasso's cache.
How can I fix this ???
Anyone have any idea?
Related
I have used Universal Image Loader for load image from a server and also getting cached it into memory for fast loading.
But from server side used the same URL for update image.
For eg., www.example.com/xyz.png is URL for the image when they needed to update image they return same URL with a different image.
In this case, Universal Image Loader return image which is previously cached in memory (I think it cached image using its related URL).
So, I needed to Change image if URL returned a different image.
This is my code which I use for load image
DisplayImageOption.java
public class DisplayImageOption {
public static DisplayImageOptions getDisplayImage() {
// .displayer(new RoundedBitmapDisplayer(0))
return new DisplayImageOptions.Builder()
.showImageOnLoading(R.mipmap.icon_place_holder)
.showImageForEmptyUri(R.mipmap.icon_place_holder)
.showImageOnFail(R.mipmap.icon_place_holder)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true).build();
}
public static DisplayImageOptions getDisplayRoundedImage() {
return new DisplayImageOptions.Builder()
.showImageOnLoading(R.mipmap.icon_place_holder)
.showImageForEmptyUri(R.mipmap.icon_place_holder)
.showImageOnFail(R.mipmap.icon_place_holder)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.displayer(new RoundedBitmapDisplayer(100)).build();
}
}
Code for Image Loading
ImageLoader.getInstance().displayImage(url, imageView, DisplayImageOption.getDisplayImage());
Thanks
In your ImageLoaderConfiguration add diskCache option.
File cacheDir = StorageUtils.getCacheDirectory(context);
long cacheAge = 10L;
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.diskCache(new LimitedAgeDiscCache(cacheDir, cacheAge)) // this will make the cache to remain for 10 seconds only
.build();
Then set it on ImageLoader and display image with your DisplayImageOption
ImageLoader.getInstance().init(config);
ImageLoader.getInstance().displayImage(url, imageView, DisplayImageOption.getDisplayImage());
What it does?
Taken from Android-Universal-Image-Loader
LimitedAgeDiscCache (Size-unlimited cache with limited files' lifetime. If age of cached file exceeds defined limit then it will be deleted from cache.)
And this piece of code is from Android-Universal-Image-Loader's LimitedAgeDiskCache.java class.
/**
* #param cacheDir Directory for file caching
* #param maxAge Max file age (in seconds). If file age will exceed this value then it'll be removed on next
* treatment (and therefore be reloaded).
*/
public LimitedAgeDiskCache(File cacheDir, long maxAge) {
this(cacheDir, null, DefaultConfigurationFactory.createFileNameGenerator(), maxAge);
}
You may like this approach as well.
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 ?
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();
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.
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();
}
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);
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);
I am using universal image loader to load images. The issue is that It does not save loaded images in cache Here is my code.
Map<String, String> headers = new HashMap<String, String>();
headers.put("key", Commons.CURRENT_ACTIVE_PROFILE.getKey());
headers.put("secret", Commons.CURRENT_ACTIVE_PROFILE.getSecret());
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(mActivity)
.imageDownloader(new CustomImageDownaloder(mActivity)).build();
//imageLoader.init(ImageLoaderConfiguration.createDefault(mActivity));
imageLoader.init(config);
imageLoader = ImageLoader.getInstance();
displayImageOptions = new DisplayImageOptions.Builder()
.extraForDownloader(headers)
.showImageForEmptyUri(R.drawable.no_preview)
.showImageOnLoading(R.drawable.no_preview)
.showImageOnFail(R.drawable.no_preview)
.cacheInMemory(true)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
The problem is when I use following line for ImageLoaderCinfiguration that creates a default settings It would work fine and saves the images in cache.
imageLoader.init(ImageLoaderConfiguration.createDefault(mActivity));
But I want to use custom settings for ImageLoaderConfiguration because I am using CustomImageDownloader to pass key/secret with URL. So i use following lines for config
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(mActivity)
.imageDownloader(new CustomImageDownaloder(mActivity)).build();
But In this case it doest not save image and if I run the app without internet it does not load the images. Any help/suggestion please?
Possible duplicate I have tried that but no use.
U can use this simple method for Image Loader view
private void initImageLoader() {
// ImageLoader initializing
DisplayImageOptions opts = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisc(true).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.defaultDisplayImageOptions(opts).build();
ImageLoader.getInstance().init(config);
}
I have resolved the issue myself. as using
.imageDownloader(new CustomImageDownaloder(mActivity)).build();
would override the default imageDownloader that is
.imageDownloader(new BaseImageDownloader(getApplicationContext())) // default
Default image downloader class contains diffrent methods to load images from web, local storage, assets etc. But the CustomImageDownaloder that i have created only contains code to get stream from web/network. So what I did is to copy and paste all the code of default BaseImageDownloader to CustomImageDownaloder and just modify the
getStreamFromNetwork(String imageUri, Object extra)
according to my requirements.
I am using the Android-Universal-Image-Loader from https://github.com/nostra13/Android-Universal-Image-Loader to load and cache images async. The problem I am facing is that i would like to open the images with the gallery or sent them to friends. For some reason my images are cached without a file extension.
I am using the current configuration
public static void initImageLoader(Context context) {
File cacheDir = StorageUtils.getOwnCacheDirectory(context, CommonUtilities.APP_DIR);
DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisc(true)
.considerExifParams(true)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.threadPriority(Thread.MAX_PRIORITY)
.discCacheExtraOptions(480, 800, CompressFormat.PNG, 75, null)
.denyCacheImageMultipleSizesInMemory()
.discCache(new UnlimitedDiscCache(cacheDir))
.defaultDisplayImageOptions(options)
.tasksProcessingOrder(QueueProcessingType.FIFO)
.build();
// Initialize ImageLoader with configuration.
ImageLoader.getInstance().init(config);
}
Hopefully anyone can help me out!
Create own FileNameGenerator which will generate file names with extension in the end and then set it into disc cache:
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
...
.discCache(new UnlimitedDiscCache(cacheDir, myGenerator))
...
.build();
Create custom file name generator
import com.nostra13.universalimageloader.cache.disc.naming.FileNameGenerator;
import static java.lang.String.valueOf;
public class HashCodeFileNameWithDummyExtGenerator implements FileNameGenerator {
#Override
public String generate(String imageUri) {
return valueOf(imageUri.hashCode()) + ".png";
}
}
Use it
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
...
.diskCache(new UnlimitedDiskCache(cacheDir, null, new HashCodeFileNameWithDummyExtGenerator()))
...
.build()
I do exactly what this guy suggests which is exactly the same as the creator of the Universal Image Loader, but I still get this error:
URI = assets://NMF0002_007.jpg
resolveUri failed on bad bitmap uri: NMF0002_007.jpg
What should I look for to ensure that the images are recognised?
I use it like this:
//get the file name
String fileName = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseHelper.FIELD_RESOURCE));
String imageUri = "assets://";
Log.d(TAG, "URI = " + imageUri + fileName);
ImageLoader.getInstance().displayImage(imageUri+fileName, holder.iv_details_resource);
This is my configuration:
//Get the imageloader.
ImageLoader imageLoader = ImageLoader.getInstance();
//Create image options.
DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheOnDisc()
.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
//Create a config with those options.
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.defaultDisplayImageOptions(options)
.discCacheExtraOptions(480, 800, CompressFormat.JPEG, 75)
.build();
//Initialise the imageloader.
imageLoader.init(config);
What am I doing wrong or missing?
Solution - I was looking for .jpg and my file extension was .JPG
If NOSTRA can post some clever things to be on the lookout for I'll mark your answer as an official answer to my silliness.