How to add an ImageLoader in android - android

I have an android game application in which each level has a 250*250(pixel) image and all the levels are in one Activity named "game1.java". because many layout features change in the levels; I call the same class using Intent and finish() the class when I wanna change the level of the game.
in that I have problem in the ram usage and I tried to use this in the game1 class:
https://github.com/nostra13/Android-Universal-Image-Loader
but I get Unfortunately each time I wanna open the activity.
this is an attribute of the game1 class:
ImageLoader imageLoader;
this part is at the start of onCreate:
super.onCreate(savedInstanceState);
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).build();
ImageLoader.getInstance().init(config);
File cacheDir = StorageUtils.getCacheDirectory(getBaseContext());
DisplayImageOptions options = new DisplayImageOptions.Builder()
.resetViewBeforeLoading(false) // default
.delayBeforeLoading(0)
.cacheInMemory(false) // default
.cacheOnDisk(true) // default
.build();
whenever I need a new image i call this function and give the strName name and extension of my image that is in assets folder. for example "image1.jpg"
private Bitmap getBitmapFromAsset(String strName)
{
String imageUri = "assets://" + strName;
//Bitmap bmp = ImageLoader.getInstance().loadImageSync(imageUri);
imageLoader.loadImage(imageUri,new SimpleImageLoadingListener(){
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
super.onLoadingComplete(imageUri, view, loadedImage);
bmp_loader=loadedImage;
}
});
return bmp_loader;
}
then I give the image to the ImageView via setImageBitmap function
where is the problem?

using my friends' helps; this is what i did eventually to fix the problem:
step 1: I setup my loader in the first activity of my game; in the onCreate:
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration
.Builder(getBaseContext())
.defaultDisplayImageOptions(defaultOptions)
.memoryCache(new LruMemoryCache(2 * 1024 * 1024))
.discCacheSize(50 * 1024 * 1024)
.discCacheFileNameGenerator(new Md5FileNameGenerator())
.build();
step 2:
in the game1.class ; after super.oncreate:
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this).build();
ImageLoader.getInstance().init(config);
File cacheDir = StorageUtils.getCacheDirectory(getBaseContext());
DisplayImageOptions options = new DisplayImageOptions.Builder()
.resetViewBeforeLoading(false) // default
.delayBeforeLoading(0)
.cacheInMemory(false) // default
.cacheOnDisk(true) // default
.build();
I gave the imageaddress that needed to a string
ax_level = "level_01.jpg";
defined my imageview
ImageView posht_safhe = (ImageView) findViewById(R.id.rook_ax);
gave the image to my imageView
String pin_url = "assets://"+ax_level;
DisplayImageOptions option = new DisplayImageOptions.Builder()
.cacheOnDisc(true)
.cacheInMemory(false )
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
ImageLoader.getInstance().displayImage(pin_url ,posht_safhe, option, new SimpleImageLoadingListener() {
#Override
public void onLoadingComplete(String imageUri, View view,
Bitmap loadedImage) {
// bitmap = loadedImage;
}
});
and finally it worked

this is very simple mistake :)
you didn't define imageLoader and the imageLoader is null when you try to call loadImage(...)!
change your code ImageLoader.getInstance().init(config); to this
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);

Related

how to use Universal-Image-Loader to load picture that the size not changed

I use the framework Universal-Image-Loader to load pictures from the Internet and the imageview is created dynamically before the practice ,but I am not satisfacted by it's result . the pictures which are showed in my app is too small not original size . I don't want to change the size of picture . So I use WebView to load by image's url then the pictures are perfect displayed ,however the app will seize up and stopped when the pictures are many.please help me ,how to set the configuration of it ? maybe the imageview should be reseted?
there are my codes:
if(url!=null){
ImageView imageView = new ImageView(activity);
imageView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
imageView.setMinimumHeight(20);
imageView.setImageResource(R.drawable.loading);
// bad method
// WebView webView=new WebView(activity);
// webView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
// group.addView(webView);
// webView.loadUrl(url);
// webView.setWebViewClient(new WebViewClient(){
// #Override
// public boolean shouldOverrideUrlLoading(WebView view,
// String url) {
// // TODO Auto-generated method stub
// view.loadUrl(url);
// return true;
// }
//
// });
ImageLoader.getInstance().displayImage(url,imageView,options);
group.addView(imageView);
// IN Display image option set image scale type exactly
// below code help you in this image will be download according to imageView //width height
public static void initImageLoader(Context context) {
DisplayImageOptions options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.picture)
.showImageForEmptyUri(R.drawable.picture)
.showImageOnFail(R.drawable.picture)
.cacheInMemory(true)
.cacheOnDisk(true)
.considerExifParams(true)
.imageScaleType(ImageScaleType.EXACTLY)
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.threadPriority(Thread.NORM_PRIORITY - 2)
.denyCacheImageMultipleSizesInMemory()
.discCacheFileNameGenerator(new Md5FileNameGenerator())
.tasksProcessingOrder(QueueProcessingType.LIFO)
.defaultDisplayImageOptions(options)
.build();
// Initialize ImageLoader with configuration.
ImageLoader.getInstance().init(config);
}

Android - GridView scroll is reloading images in universal image loader

I'm using universal image loader, but the images are reloaded every time I scroll up and down.
I'm using below code.
Configuration - >
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext())
.memoryCache(new WeakMemoryCache())
.denyCacheImageMultipleSizesInMemory()
.discCacheFileNameGenerator(new Md5FileNameGenerator())
.tasksProcessingOrder(QueueProcessingType.LIFO)
// .enableLogging() // Not necessary in common
.build();
// Initialize ImageLoader with configuration.
ImageLoader.getInstance().init(config);
Options->
options = new DisplayImageOptions.Builder()
.resetViewBeforeLoading()
.imageScaleType(ImageScaleType.EXACTLY)
.cacheInMemory(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
view ->
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View workingview = inflater.inflate(R.layout.gridview_item_photo_icon, null);
ImageView imageView = (ImageView) workingview.findViewById(R.id.picture);
ImageAware imageAware = new ImageViewAware(imageView, false);
imageLoader.displayImage("file://" + imageUrls.get(position), imageAware, options, new SimpleImageLoadingListener());
return workingview;
}
Please let me know where I'm going wrong.
There is a limit of chache in android around 1MB of image cashing it clears cache and download again that is why it reloads again images.
Its is proper way if you are not downloading images in your SD card of phone memory.
You can not hold much data in caching.

Cache downloaded image in ListView

I have a ListView with an adapter that loads various data from an API. One of the data is a URL to an image online. I download the image and set it in my ImageView in the adapter.
The problem is though, when I scroll up and down in the ListView, images are re-downloaded and there is a significant lag when doing that. Also, for a split second, it incorrectly displays the wrong image.
I need to somehow cache these images to only download once and properly set them in that ListView - How do I do that?
EDIT:
I use universal image loader to load my images like this:
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(imageUrl, viewHolder.thumbnailImageView);
But it does not seem to cache them... Do I have to do something additional?
Use ImageLoaders
Glide
ImageView imageView = (ImageView) findViewById(R.id.my_image_view);
Glide.with(this).load("http://goo.gl/gEgYUd").into(imageView);
Simple Image load. Check the link you can use them with listeners.
You can also try:
picasso
Android-Universal-Image-Loader
EDIT: As the OP said he uses UIL .
]You should use Image Aware.
You can have your own configuration with high cache memory something like this.
public void initializeImageLoader(final Context sContext) {
final ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(sContext)
.memoryCacheExtraOptions(480, 800) // default = device screen dimensions
.taskExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
.taskExecutorForCachedImages(AsyncTask.THREAD_POOL_EXECUTOR)
.threadPoolSize(3) // default
.threadPriority(Thread.NORM_PRIORITY - 1) // default
.tasksProcessingOrder(QueueProcessingType.FIFO) // default
.denyCacheImageMultipleSizesInMemory()
.memoryCache(new UsingFreqLimitedMemoryCache(50 * 1024 * 1024)) // default
.memoryCacheSize(50 * 1024 * 1024)
.imageDownloader(new BaseImageDownloader(sContext)) // default
.defaultDisplayImageOptions(DisplayImageOptions.createSimple()) // default
.build();
ImageLoader.getInstance().init(config);
}
Use this initialization before you get instance.
initializeImageLoader(context);
ImageLoader imageLoader = ImageLoader.getInstance();
Set Options for your loader.
final DisplayImageOptions options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.loading)
.showImageForEmptyUri(R.drawable.noimage)
.showImageOnFail(R.drawable.noimage)
.resetViewBeforeLoading(false) //default
.bitmapConfig(Bitmap.Config.RGB_565)
.cacheInMemory(true)
.cacheOnDisk(false) //default
.build();
And set it to your loader:
final ImageAware imageAware = new ImageViewAware(viewHolder.thumbnailImageView, false);
imageLoader.displayImage(imageUrl, imageAware, options);

Universal Image Loader rounded image only when scroll

I'm using Universal Image Loader in a ListView, It works perfectly the first time, but the rest of the time, the image has no rounded corners. Only if I scroll the image has rounded borders again.
This is my code:
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
context).threadPriority(Thread.NORM_PRIORITY - 2)
.denyCacheImageMultipleSizesInMemory()
.discCacheFileNameGenerator(new Md5FileNameGenerator())
.tasksProcessingOrder(QueueProcessingType.LIFO).enableLogging()
.build();
// Initialize ImageLoader with configuration.
ImageLoader.getInstance().init(config);
DisplayImageOptions options = new DisplayImageOptions.Builder()
.displayer(new RoundedBitmapDisplayer(50))
.showStubImage(R.drawable.ic_app)
.showImageForEmptyUri(R.drawable.camera)
.showImageOnFail(R.drawable.ic_error).cacheInMemory().cacheOnDisc()
.build();
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.listmessages_row, null);
}//End if
ImageView avatar = (ImageView) convertView.findViewById(R.id.ImageView_MessageRow);
ImageView avatarEmpty = (ImageView) convertView.findViewById(R.id.ImageView_PhotoProfileEmpty);
final int positionAux = position;
if (listItems.get(position).avatar.equals("no_avatar")){
avatarEmpty.setVisibility(View.VISIBLE);
avatar.setVisibility(View.GONE);
}else{
avatarEmpty.setVisibility(View.GONE);
avatar.setVisibility(View.VISIBLE);
imageLoader.displayImage(IMAGES + listItems.get(position).avatar, avatar, options);
}//End if-else
return convertView;
}//End getView
I answer myserlf, I modified the options of displayImageOtions and it works perfectly all the times. I only deleted this line: cacheInMemory()
Now my display image options are:
options = new DisplayImageOptions.Builder()
.displayer(new RoundedBitmapDisplayer(50))
.showStubImage(R.drawable.ic_app)
.showImageForEmptyUri(R.drawable.camera)
.showImageOnFail(R.drawable.ic_error)
.cacheOnDisc()
.build();

Android Universal Image Loader - how do I set the specs correctly?

I have an app that loads a lot of big images remotely.
When I use nostra's Universal Image Loader (https://github.com/nostra13/Android-Universal-Image-Loader) I often get Out Of Memory errors. I don't know how I should set up the imageloader to prevent this.
This is my current ImageLoader specs:
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.enableLogging()
.memoryCache(new WeakMemoryCache())
.build();
this.imgDispOpts = new DisplayImageOptions.Builder()
.cacheInMemory()
.cacheOnDisc()
.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
.build();
this.imageLoader = ImageLoader.getInstance();
this.imageLoader.init(config);
And yes, I pass imgDispOpts when calling displayImage().
Try not cache in memory, use EXACTLY scale type and RGB_565 for bitmap decoding.
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.enableLogging()
.build();
this.imgDispOpts = new DisplayImageOptions.Builder()
.cacheOnDisc()
.imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
I tried to reduce the bitmap size in the bitmap decoder, which worked for me.
In package com.nostra13.universalimageloader.core.decode, open BaseImageDecoder.java,
public Bitmap decode(ImageDecodingInfo decodingInfo) throws IOException {
Bitmap decodedBitmap;
ImageFileInfo imageInfo;
InputStream imageStream = getImageStream(decodingInfo);
try {
imageInfo = defineImageSizeAndRotation(imageStream, decodingInfo);
imageStream = resetStream(imageStream, decodingInfo);
Options decodingOptions = prepareDecodingOptions(imageInfo.imageSize, decodingInfo);
// add in the decodingOptions here:
decodingOptions.inSampleSize = 10; // or any number
// or you can calculate the resample rate by using the screen size / grid size and the image size
decodedBitmap = BitmapFactory.decodeStream(imageStream, null, decodingOptions);
} finally {
IoUtils.closeSilently(imageStream);
}
if (decodedBitmap == null) {
L.e(ERROR_CANT_DECODE_IMAGE, decodingInfo.getImageKey());
} else {
decodedBitmap = considerExactScaleAndOrientaiton(decodedBitmap, decodingInfo, imageInfo.exif.rotation, imageInfo.exif.flipHorizontal);
}
return decodedBitmap;
}
Try the below configuration
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.enableLogging()
discCacheExtraOptions(maxImageWidthForDiscCache, maxImageHeightForDiscCache, CompressFormat.PNG, 0);
.memoryCache(new WeakMemoryCache())
.build();
this.imgDispOpts = new DisplayImageOptions.Builder()
.cacheInMemory()
.cacheOnDisc()
.imageScaleType(ImageScaleType.EXACTLY)
.build();
You can also use Lazy Loading of images.https://github.com/thest1/LazyList.
Universal Image loader based on Fedor Vlasov's project LazyList. Improved version of LazyList.
You may try this, it worked well for me:
ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(context)
//Add these lines to your ImageLoader configuration
.threadPriority(Thread.NORM_PRIORITY - 2);
.denyCacheImageMultipleSizesInMemory();
.diskCacheExtraOptions(150, 150, null); // You may change image resolution to fit your needs
ImageLoader.getInstance().init(config.build());

Categories

Resources