How to increase the image size in Universal image loader? - android

Using an Universal Image loader i'm trying to increase the size of the image which i got from JSON url and i tried all possible methods available in valuable stackoverflow but didn't get the right solution to increase the image size so here i am posting my code and correct me by giving your suggestions.Thanks in advance
public ImageSlideAdapter(FragmentActivity activity, List<Product> products,
HomeFragment homeFragment) {
this.activity = activity;
this.homeFragment = homeFragment;
this.products = products;
options = new DisplayImageOptions.Builder()
.showImageOnFail(R.drawable.ic_error) .bitmapConfig(Bitmap.Config.ARGB_8888)
.imageScaleType(ImageScaleType.EXACTLY)
.showImageForEmptyUri(R.drawable.ic_empty).cacheInMemory() .displayer(new RoundedBitmapDisplayer(20))
.cacheOnDisc().build();
imageListener = new ImageDisplayListener();
}

Related

ImageLOader Android

I am using Universal imageloader class with RoundedBitmapDisplayer options. The RoundedBitmapDisplayer takes a particular value (here 1000) whose documentation is not available. Does anyone know what the value represents ?
private DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheInMemory(true).cacheOnDisk(true).resetViewBeforeLoading(true)
.displayer(new RoundedBitmapDisplayer(1000)).showImageForEmptyUri(R.drawable.ico_user)
.showImageOnFail(R.drawable.ico_user).showImageOnLoading(R.drawable.ico_user).build();

DisplayImageOptions configuration conflict in universal image loader

private void setImageloadConfig() {
defaultOption = new DisplayImageOptions.Builder()
.bitmapConfig(Config.RGB_565).resetViewBeforeLoading(false)
.cacheInMemory(true).cacheOnDisk(true);
configuration = new ImageLoaderConfiguration.Builder(context).denyCacheImageMultipleSizesInMemory()
.threadPoolSize(3).memoryCache(new LruMemoryCache(IMG_MAX_SIZE))
.memoryCache(new UsingFreqLimitedMemoryCache(IMG_MAX_SIZE)).memoryCacheSize(IMG_MAX_SIZE)
.memoryCacheSizePercentage(13).diskCache(new UnlimitedDiscCache(new File(IMAGE_FILE_PATH)))
.diskCacheSize(50 * 1024 * 1024).diskCacheFileNameGenerator(new HashCodeFileNameGenerator())
.defaultDisplayImageOptions(defaultOption.build())
.imageDownloader(new BaseImageDownloader(context, 5 * 1000, 30 * 1000)).build();
ImageLoader.getInstance().init(configuration);
}
In global activity, I have set DisplayImageOptions, but there is a problem, if I want to config showImageOnLoading, showImageForEmptyUri and showImageOnFail, how can solve it, because in difference issue. I want to set different image, but if I set it in specific activity, it will cover the global configuration.
The problem exists in code part2.
DisplayImageOptions options = new DisplayImageOptions.Builder()
.bitmapConfig(Config.RGB_565).resetViewBeforeLoading(false)
.cacheInMemory(true).cacheOnDisk(true)
.showImageOnLoading(R.drawable.home_list_img_picture)
.showImageForEmptyUri(R.drawable.home_list_img_picture)
.showImageOnFail(R.drawable.home_list_img_picture)
.build();
ImageLoader.getInstance().displayImage(imgPath,iamge_photo,options);
If I move the DisplayImageOptions configuration from global activity to specific activity, it's OK, but causes another problem. When I switch activities, the image component will flicker, which is OK, when configured in global activity, how can I solve this confict, any suggestions?

android - delay while loading Bitmaps into ArrayList using UniversalImageLoader

I need to load Bitmaps into ArrayList, then convert it to Bitmap[] and pass into ArrayAdapter to inflate ListView. I use UniversalImageLoader library and here is my code:
final ArrayList<Bitmap> imgArray = new ArrayList<>(); //before the method scope, as a class field
//...some code...
File cacheDir = StorageUtils.getOwnCacheDirectory(
getApplicationContext(),
"/sdcard/Android/data/random_folder_for_cache");
DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheInMemory(true).cacheOnDisc(true).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
getApplicationContext()).defaultDisplayImageOptions(options)
//.discCache(new FileCounterLimitedCache(cacheDir, 100)) - I commented it 'cause FileCounterLimitedCache isn't recognized for some reason
.build();
ImageLoader.getInstance().init(config);
for (int num=0;num<4;num++) {
ImageLoader imageLoader = ImageLoader.getInstance();
final int constNum = num;
imageLoader.loadImage("http://example.com/sample.jpg", new SimpleImageLoadingListener()
{
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage)
{
imgArray.add(constNum, loadedImage);
}
});
}
But I have some issues to struggle. Firstly, it often returns error (IndexOutOfBoundsException - current index exceeds size of ArrsyList) when first run. Then after some time (about a minute) the size of ArrayList is 1 (I check it with Toast), and then when run again right at once, it's already 4 (as it needs to be). Strange. But the main thing I need that the ArrayList is first filled and then all the other actions are done (that they be delayed and I don't have errors on the first run). How to do it?
And what to do if somebody doesn't have SD card? Btw, I couldn't find the created cache folder on my SD...
You can't add the elements in the way you're trying to. If for example the 2nd image finishes loading first, your code will correctly throw an IndexOutOfBoundsException as the location you're trying to add at is beyond the current size - see the documentation
You might be better off using an array initialised to the number of elements seeing as you know it's 4 elements - e.g.
final Bitmap[] imgArray = new Bitmap[4];
Then add the elements in your onLoadingComplete() using
imgArray[constNum] = loadedImage;
You can use a SparseArray instead of an ArrayList to avoid the IndexOutOfBoundsException.
I assume this is what you are after:
final SparseArray<Bitmap> imgArray = new SparseArray<>(); //before the method scope, as a class field
int numberOfImages;
int numberOfLoadedImages;
//...some code...
File cacheDir = StorageUtils.getOwnCacheDirectory(
getApplicationContext(),
"/sdcard/Android/data/random_folder_for_cache");
DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheInMemory(true).cacheOnDisc(true).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
getApplicationContext()).defaultDisplayImageOptions(options)
//.discCache(new FileCounterLimitedCache(cacheDir, 100)) - I commented it 'cause FileCounterLimitedCache isn't recognized for some reason
.build();
ImageLoader.getInstance().init(config);
numberOfImages = 4;
numberOfLoadedImages = 0;
for (int num=0;num<4;num++) {
ImageLoader imageLoader = ImageLoader.getInstance();
final int constNum = num;
imageLoader.loadImage("http://example.com/sample.jpg", new SimpleImageLoadingListener()
{
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage)
{
imgArray.put(constNum, loadedImage);
numberOfLoadedImages++;
if(numberOfImages == numberOfLoadedImages)
{
//Do all the other actions
}
}
});
}
Universal Image Loader library contains the following method:
public void displayImage(java.lang.String uri, android.widget.ImageView imageView)
Which can be passes the image url and the ImageView to display the image on it.
plus to that, if later the same ImageView passed to the method but with a different url two thing can happen:
if old image already downloaded, normally the new image will be set to the ImageView.
if old image still downloading the library will cancel the http connection that is downloading the old image. and start downloading
the new image. (can be observed in the LogCat). this behaviour happens
when using an adapter.
Method call:
ImageLoader.getInstance().displayImage("http://hydra-media.cursecdn.com/dota2.gamepedia.com/b/bd/Earthshaker.png", imageView1);
Configuration:
Caching will not work if the defaultDisplayImageOptions not specified. which tells the library where to save those image. because this library has options to load images from Assets, Drawables or Internet:
DisplayImageOptions opts = new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisk(true).build();
With this option the images will be saved in app. internal memory.
don't worry weather the device have an external memory or not.
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this)
.defaultDisplayImageOptions(opts)
.memoryCache(new LruMemoryCache(2 * 1024 * 1024))
.memoryCacheSize(2 * 1024 * 1024)
.diskCacheSize(50 * 1024 * 1024)
.diskCacheFileCount(100)
.writeDebugLogs()
.build();
ImageLoader.getInstance().init(config);
I created a working github repository for it. check it out.

Add array of URLs to imageview

I have the following code to get URL from HTML file using jsoup and save in array:
Element table2 = document.select("TABLE").get(1);
for (Element td : tr.select("td")){
Element img = td.select("img").first();
if (img == null){
continue;
}
String imgRelPath = img.attr("src");
images.add("http://hostname.com"+imgRelPath);
}
}
objImages = images.toArray();
The array has:
http://hostname.com/hobbit/gifs/static/green.gif
http://hostname.com/hobbit/gifs/static/green.gif
http://hostname.com/hobbit/gifs/static/clear.gif
http://hostname.com/hobbit/gifs/static/clear.gif
http://hostname.com/hobbit/gifs/static/green.gif
http://hostname.com/hobbit/gifs/static/red.gif
http://hostname.com/hobbit/gifs/static/green.gif
http://hostname.com/hobbit/gifs/static/green.gif
http://hostname.com/hobbit/gifs/static/green.gif
http://hostname.com/hobbit/gifs/static/green.gif
No I need get all images from url and put into imageView one after the other. Any idea?
Thanks in advance.
EDIT:
I'm calling Picasso.with in Async Task on onPostExecute in MainActivity:
#Override
protected void onPostExecute(Void result) {
ImageView estados = (ImageView) findViewById(R.id.estados);
Picasso.with(MainActivity.this).load("http://salesianoscarmona.com/nuevo/templates/rt_modulus_j15/images/icons/icon-crank.png").into(estados);
mProgressDialog.dismiss();
}
I have the import in the header:
import com.squareup.picasso.Picasso;
there str several great libraries that download and set image to ImageView from url:
http://square.github.io/picasso
or
https://github.com/bumptech/glide
Both are great. With picasso you can easily set url to image view and it will do the job example
Picasso.with(context).load("http://hostname.com/hobbit/gifs/static/green.gif").into(imageView);
Hope this helps
Use Universal image loader for downloading images asynchronously.
http://github.com/nostra13/Android-Universal-Image-Loader
The Library itself has a sample code to download image.you may refer it..
After downloading library add library with your project and insert the below code at necessary place
String final_url="www.google.com/.....";
ImageView image;
ImageLoader imageloader = ImageLoader.getInstance();
imageloader.init(ImageLoaderConfiguration.createDefault(context));
DisplayImageOptions options; = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error)
.resetViewBeforeLoading(true).cacheOnDisk(true)
.imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565).considerExifParams(true)
.cacheInMemory(true)
.displayer(new FadeInBitmapDisplayer(300)).build();
imageloader.displayImage(final_url, image);

Android video thumbnail displaying in a ListAdapter

I'm currently loading all videos on the device into a custom ListAdapter that shows the thumbnail for the Video + more. I've noticed as I add more and more videos it gets slower to initiate. This is how my List adapter looks like:
public class VideoListAdapter extends ArrayAdapter<Video> {
private ArrayList<Video> allVideos;
private HashMap<String, Bitmap> bitmapCache;
public VideoListAdapter(Context context, ArrayList<Video> videos) {
super(context, R.layout.video_list_item, videos);
this.allVideos = videos;
/* Cache the thumbnails */
setUpBitmaps();
}
private void setUpBitmaps() {
bitmapCache = new HashMap<String, Bitmap>(allVideos.size());
for(Video video : allVideos){
bitmapCache.put(video.getDATA(), ThumbnailUtils.createVideoThumbnail(video.getDATA(), Thumbnails.MICRO_KIND));
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
row = inflater.inflate(R.layout.video_list_item, null);
} else {
row = convertView;
}
Video tmpVideo = allVideos.get(position);
String TITLE = tmpVideo.getTITLE();
long vidDur = Long.valueOf(tmpVideo.getDURATION());
String DURATION = String.format(Locale.getDefault(),"%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(vidDur) -
TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(vidDur)),
TimeUnit.MILLISECONDS.toSeconds(vidDur) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(vidDur)));
String filepath = tmpVideo.getDATA();
Bitmap thumbnail = bitmapCache.get(filepath);
TextView tvTitle = (TextView) row.findViewById(R.id.tvListItemVideoTitle);
TextView tvDuration = (TextView) row.findViewById(R.id.tvListItemVideoDuration);
ImageView ivThumbnail = (ImageView) row.findViewById(R.id.ivListItemVideoThumbnail);
tvTitle.setText(TITLE);
tvDuration.setText(DURATION);
if(thumbnail != null){
ivThumbnail.setImageBitmap(thumbnail);
}
return row;
}
}
How should load the thumbnails to decrease the time it takes to load the list adapter? Currently on my device it takes 3-4 seconds before the activity showing the adapter shows, and I only have about 15 videos.
Any suggestions would be greatly appreciated.
Marcus
Instead of showing videos in listview, Get the thumbnail for your video by passing video path and show them in the ListView.. Use this code to get thumbnail. And also use lazylist to shows images properly.
Bitmap thumb = ThumbnailUtils.createVideoThumbnail(path,
MediaStore.Images.Thumbnails.MINI_KIND);
You can use lazyloading for this,LazyLoading will make your list scroll fast.Follow this library it will help:
https://github.com/nostra13/Android-Universal-Image-Loader
Steps of using lazy loading :
1.)Download jar file from this link:
http://www.java2s.com/Code/Jar/u/Downloaduniversalimageloader161withsrcjar.htm
2.)Create Application File :
import android.app.Application;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
public class MyApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
// UNIVERSAL IMAGE LOADER SETUP
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisc(true).cacheInMemory(true)
.imageScaleType(ImageScaleType.EXACTLY)
.displayer(new FadeInBitmapDisplayer(300)).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
getApplicationContext())
.defaultDisplayImageOptions(defaultOptions)
.memoryCache(new WeakMemoryCache())
.discCacheSize(100 * 1024 * 1024).build();
ImageLoader.getInstance().init(config);
// END - UNIVERSAL IMAGE LOADER SETUP
}
}
3.)On your activity in whcih you want to use ,write this it onCreate():
DisplayImageOptions options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.iclauncher) // resource or
// drawable
.showImageForEmptyUri(R.drawable.iclauncher) // resource or
// drawable
.showImageOnFail(R.drawable.iclauncher) // resource or
// drawable
.resetViewBeforeLoading(false) // default
.delayBeforeLoading(1000).cacheInMemory(true) // default
.cacheOnDisc(true) // default
.considerExifParams(true) // default
.imageScaleType(ImageScaleType.IN_SAMPLE_INT) // default
.bitmapConfig(Bitmap.Config.ARGB_8888) // default
.displayer(new SimpleBitmapDisplayer()) // default
.handler(new Handler()) // default
.build();
imageLoader = ImageLoader.getInstance();
4.)on your adapter write this:
imageLoader.displayImage(alist.get(position).getThumbnails(),
holder.ivImage, options, null); // alist.get(position).getThumbnails() is the url of the thumbnail and holder.ivImage is the reference of the imageview where thumbnail is to be placed

Categories

Resources