I am using Universal ImageLoader for downloading large images from server and displaying them in coverflow. Issue I am facing here is that I am unable to set custom size for my image. It just takes whole screen. For example, I am downloading image of size 500 x 1200 - and I want to display it of size 300 x 300. But it takes full display. Please help me with this issue as I am stuck for more than 3 days. Thanks.
Code
public class HomeCoverFlow {
Context mContext;
public CoverFlow coverFlow;
ImageAdapter coverImageAdapter;
ImageLoader imageLoader = ImageLoader.getInstance();
DisplayImageOptions options;
/** Called when the activity is first created. */
public HomeCoverFlow(Context context)
{
mContext = context;
options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.flyer_placeholder)
.showImageForEmptyUri(R.drawable.flyer_placeholder)
.imageScaleType(ImageScaleType.EXACTLY)
.cacheInMemory(true)
.build();
coverFlow = new CoverFlow(context);
coverImageAdapter = new ImageAdapter(mContext);
coverFlow.setAdapter(coverImageAdapter);
coverFlow.setSpacing(-25);
coverFlow.setSelection(2, true);
coverFlow.setAnimationDuration(1000);
coverFlow.setGravity(Gravity.CENTER_VERTICAL);
// HEIGHT
coverImageAdapter.coverflowHeight = 100; //display.getHeight() / 3;
//WIDTH
coverImageAdapter.coverflowWidth = 100;// display.getWidth() / 2;
}
A method in adapter to create item views, Here I use imageloader to download image and display
public View getView(int position, View convertView, ViewGroup parent) {
FeaturedFlyerData data = (FeaturedFlyerData) getItem(position);
if(data.flyerImage == null)
{
setNewImage(position);
}
//see text or image
if(data.displayImage)
{
data.flyerImage.setBackgroundColor(Color.BLACK);
imageLoader.displayImage(data.url, data.flyerImage, options, null);
}
return data.flyerImage;
}
void setNewImage(int position)
{
FeaturedFlyerData data = (FeaturedFlyerData) getItem(position);
data.flyerImage = new ImageView(mContext);
data.flyerImage.layout(0, 10, 200,350);
data.flyerImage.setScaleType(ScaleType.CENTER_INSIDE);
data.flyerImage.setTag(Integer.toString(position));
data.flyerImage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
imageClicked(Integer.parseInt(v.getTag().toString()));
}
});
}
}
I don't know what else code snippet to provide here. Please comment if you need any further clarifications. Thanks.
I am using following code to display custom size images in coverflow using universal imageloader.
In constructor, set DisplayImageOptions as:
DisplayImageOptions options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.flyer_placeholder)
.showImageForEmptyUri(R.drawable.flyer_placeholder)
.imageScaleType(ImageScaleType.EXACTLY)
.cacheInMemory(true)
.build();
//set coverflow full screen, and images size.
coverFlow.setSpacing(-25);
coverFlow.setAnimationDuration(1000);
coverFlow.setGravity(Gravity.CENTER_VERTICAL);
coverFlow.setLayoutParams(new CoverFlow.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
// GET SCREEN SIZE
WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
DisplayMetrics dm = new DisplayMetrics();
display.getMetrics(dm);
//Here I am setting image size using my custom adapter in "dp". Avoid to use pixels as things will mess up for different screen sizes
coverImageAdapter.coverflowWidth = (int) Math.ceil(dm.widthPixels * (dm.densityDpi / 160.0));
coverImageAdapter.coverflowHeight = (int) Math.ceil(dm.heightPixels * (dm.densityDpi / 160.0)) / 2;
In adapter's setNewImage method (called in getView), use Gallery.LayoutParams:
void setNewImage(int position)
{
FeaturedFlyerData data = (FeaturedFlyerData) getItem(position);
data.flyerImage = new ImageView(mContext);
data.flyerImage.setLayoutParams(new Gallery.LayoutParams(coverflowWidth, coverflowHeight));
data.flyerImage.setScaleType(ScaleType.CENTER_INSIDE);
}
Related
I have a listivew that display a bunch of images. am using Universal Image Loader to load this images from files to imageviews.
This images have different dimensions and i want all of them to have same width but different height in respect to each image aspect ratio.
To achieve this, i have tried setting the following to my imageview
<ImageView
android:layout_width = "400dp"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:adjustViewBounds="true"/>
The issue with this method is that there is a lot of flickering when one scrolls the listview since imageview height is not known in advance and images have to be scaled first using my width to calculate each image height in respect to it's aspect ratio.
How can i calculate each image height in advance instead of letting imageview handle it?
if i have an image which is 400 X 700, and i want the imageview to be 300px wide, how can i calculate imageview's height using my image dimension and maintain image aspect ratio? this can help avoid flickering wnen one scroll the listview.
The reason for this flicker is that, in listview list items are reused. When re-used, the imageviews in the list item retains the old image reference which is displayed first. Later on once new image is downloaded, it starts to show. this causes the flickering behavior.
To avoid this flickering issue, always clear the old image reference from the imageview when it is getting reused.
In your case, add holder.image.setImageBitmap(null); after holder = (ViewHolder) convertView.getTag();
So, your getView() method will look like:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
...
if (convertView == null) {
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(viewResourceId, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
holder.image.setImageBitmap(null)
}
...
return convertView;
}
After hours of research, i was able to know the method that i can use to calculate new imageview height while maintaining image aspect ratio.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
//Returns null, sizes are in the options variable
BitmapFactory.decodeFile("/sdcard/image.png", options);
int width = options.outWidth;
int height = options.outHeight;
//calculating image aspect ratio
float ratio =(float) height/(float) width;
//calculating my image height since i want it to be 360px wide
int newHeight = Math.round(ratio*360);
//setting the new dimentions
imageview.getLayoutParams().width = 360;
imageview.getLayoutParams().height = newHeight;
//i'm using universal image loader to display image
imaheview.post(new Runnable(){
ImageLoader.getInstance().displayImage(imageuri,imageview,displayoptions);
});
You can do something like this :
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
//Returns null, sizes are in the options variable
BitmapFactory.decodeFile("/sdcard/image.png", options);
int width = options.outWidth;
int height = options.outHeight;
//If you want, the MIME type will also be decoded (if possible)
String type = options.outMimeType;
How I solved it was by creating a Bitmap[] array variable to store images, then in adapter's getView(), I used position to check if image in Bitmap[] array is null or has value. If it is has value, then I use the value instead of calling the new DownloadImageTask() construct again.
For example:
YourCustomArrayAdapter.java
public class MyCustomArrayAdapter extends ArrayAdapter {
private static Bitmap[] myListViewImageViewsArray = new Bitmap[listViewItemsArray.length];
private String[] myListViewImageURLsArray = new String[listViewItemsArray.length]{
"image_url_1",
"image_url_2",
...
...
};
#Override
public View getView(int position, View view, ViewGroup parent){
CustomViewHolder vHolder;
if(view == null){
view = inflater.inflate(R.layout.movies_coming_soon_content_template, null, true);
vHolder = new CustomViewHolder();
vHolder.imageView = (AppCompatImageView) view.findViewById(R.id.my_cutom_image);
vHolder.imageUrl = "";
view.setTag(vHolder);
}
else{
vHolder = (CustomViewHolder)view.getTag();
// -- Set imageview src to null or some predefined placeholder (this is not really necessary but it might help just to flush any conflicting data hanging around)
vHolder.imageView.setImageResource(null);
}
// ...
// -- THIS IS THE MAIN PART THAT STOPPED THE FLICKERING FOR ME
if(myListViewImageViewsArray[position] != null){
vHolder.imageView.setImageBitmap(myListViewImageViewsArray[position]);
}else{
new DownloadImageTask(position, vHolder.imageView).execute(vHolder.imageUrl);
}
// -- END OF THE FLICKERING CONTROL
}
}
Then, in your image downloader construct, after downloading the image, make an insertion into the Bitmap[] image array for that position. For example:
YourImageDownloaderClass.java
public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
AppCompatImageView imageView;
int position;
public DownloadImageTask(int position, AppCompatImageView imageView){
this.imageView = imageView;
this.position = position;
}
#Override
protected Bitmap doInBackground(String...urls) {
String urlOfImage = urls[0];
Bitmap logo = null;
try{
logo = BitmapFactory.decodeStream((InputStream) new URL(urlOfImage).getContent());
}catch(Exception e){
e.printStackTrace();
}
return logo;
}
#Override
protected void onPostExecute(Bitmap result){
if(result != null) {
YourCustomArrayAdapter.myListViewImageViewsArray [position] = result;
imageView.setImageBitmap(result);
}else{
YourCustomArrayAdapter.myListViewImageViewsArray [position] = null;
imageView.setImageResource(null);
}
}
}
my suggestion is to use grid view to avoid flickering of images it will load at first time if it is same url , it will load from cache
Glide.with(mContext)
.load(item.getImageUrl())
.into(holder.mIVGridPic);
I'm using Universal Image Loader to load images from a backend to display user images in a list; however, if the icon shows up multiple times, the Universal Image Loader doesn't fill out all the views.
[User Image 1] - No image
[User Image 1] - No Image
[User Image 2] - Fine
[User Image 2] - No Image
[User Image 3] - Fine
[User Image 1] - Fine
And then on another screen:
[User Image 1] - Fine
[User Image 1] - No image
I'm using cacheInMemory and cacheOnDisk, which seemed to improve it. As before it was only displaying it in one of the views, instead of most, but I need all of them to work.
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory( true )
.cacheOnDisk( true )
.build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder( this )
.threadPoolSize( 3 )
.defaultDisplayImageOptions( defaultOptions )
.build();
ImageLoader.getInstance().init( config );
I'm not using a ListView for this task, I'm using a ScrollView and inflating it with a custom layout.
private View createSmallActivity( LayoutInflater inflater, final Event activity ) {
final View view;
view = inflater.inflate( R.layout.activity_posted_small, null );
...
// The owner's image.
if( activity.ownerImageUrl != null ) {
Loader.loadImage( getActivity(),
activity.ownerImageUrl,
R.drawable.postedactivitysmall_imageprofileempty,
( ImageView ) view.findViewById( R.id.profileImage ) );
}
return view;
}
// Loader.loadImage
// Setting the targetSize, and masking the image with a resource.
public static void loadImage( Context context, String url, int resource, ImageView view ) {
Drawable d = context.getResources().getDrawable( resource );
int h = d.getIntrinsicHeight();
int w = d.getIntrinsicWidth();
ImageSize targetSize = new ImageSize( w, h );
ImageLoader.getInstance().loadImage( url, targetSize, new MaskImageLoader( context, view, resource ) );
}
Any idea on how I can improve the Universal Image Loader to ensure all the views are correctly filled out?
Thanks for your help!
It's because Universal Image Loader cancel previous requests with same url (used as id). To prevent this behaviour, replace
ImageLoader.getInstance().loadImage( url, targetSize, new MaskImageLoader( context, view, resource ) );
by
ImageLoader.getInstance().displayImage(url,
new NonViewAware(new ImageSize(w, h), ViewScaleType.CROP),
new MaskImageLoader(context, view, resource));
I recommend you use ListView. Maybe you should declare ImageLoader globally. then use it.
ImageLoader imageLoader = ImageLoader.getInstance();
...
imageLoader.displayImage(imageUri, imageView);
Long time reader, first time poster. I'm very new to Android development and am having trouble getting images to show when using AsyncTask to insert ImageViews (containing Bitmaps) into a LinearLayout. This is all triggered in the onCreate() method of an Activity I have.
The ImageViews (+Bitmaps) are definitely getting added via AsyncTask to my LinearLayout parent. However, the images don't show properly when I start my Activity. Sometimes an image or two (out of 3+) will display and sometimes none will show. All the images display properly after I fiddle with the UI, such as by bringing up and hiding the keyboard. I suspect that the LinearLayout and/or ImageViews may not be resizing to contain and show all the new children, but I tried many combinations of invalidate() and requestLayout() at the places I marked as "LOCATION1" and "LOCATION2" in attempt to trigger redraws.
Would anyone help on ensuring all images are displayed properly after onCreate() and after each AsyncTask is complete? Thanks a bunch. I'll try to be succinct with my code snippets...
This is my layout XML. I am adding my ImageViews to the LinearLayout with id "horizontal":
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<EditText
... />
<HorizontalScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<LinearLayout
android:id="#+id/horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</LinearLayout>
</HorizontalScrollView>
This is some of my onCreate() code. Where I create an AsyncTask for every image I want displayed.
protected void onCreate(Bundle savedInstanceState) {
...
LinearLayout horizontal = (LinearLayout) findViewById(R.id.horizontal);
...
//an array of absolute file paths to JPGs in storage
ArrayList<String> images = report.getImageMain();
PhotoBitmapTask task = null; //extension of AsyncTask
for (int i = 0; i < images.size(); i++) {
task = new PhotoBitmapTask(getApplicationContext(), horizontal, images);
task.execute(i);
//LOCATION1
}
...
}
This is my extension of AsyncTask.
//a bunch of imports
public class PhotoBitmapTask extends AsyncTask<Integer, Void, Bitmap> {
private Context context;
private WeakReference<ViewGroup> parent;
private ArrayList<String> images;
private int data;
public PhotoBitmapTask(Context context, ViewGroup parent, ArrayList<String> images) {
super();
this.context = context;
this.parent = new WeakReference<ViewGroup>(parent);
this.images = images;
this.data = 0;
}
#Override
protected Bitmap doInBackground(Integer... params) {
data = params[0];
return getBitmapFromFile(images.get(params[0]), 600, 600);
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (context != null && parent != null && result != null) {
ViewGroup viewGroup = parent.get();
if (viewGroup != null) {
ImageView imageView = PhotoBitmapTask.getImageView(context);
imageView.setImageBitmap(result);
viewGroup.addView(imageView);
//LOCATION2
}
}
}
public static Bitmap getBitmapFromFile(String filePath, int maxHeight,
int maxWidth) {
// check dimensions for sample size
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
// calculate sample size
options.inSampleSize = getSampleSize(options, maxHeight, maxWidth);
// decode Bitmap with sample size
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(filePath, options);
}
public static int getSampleSize(BitmapFactory.Options options,
int maxHeight, int maxWidth) {
final int height = options.outHeight;
final int width = options.outWidth;
int sampleSize = 1;
if (height > maxHeight || width > maxWidth) {
// calculate ratios of given height/width to max height/width
final int heightRatio = Math.round((float) height / (float) maxHeight);
final int widthRatio = Math.round((float) width / (float) maxWidth);
// select smallest ratio as the sample size
if (heightRatio > widthRatio)
return heightRatio;
else
return widthRatio;
} else
return sampleSize;
}
public int getData() {
return this.data;
}
public static ImageView getImageView(Context context) {
// width and height
final LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
// margins
params.setMargins(20, 20, 20, 20);
final ImageView view = new ImageView(context);
view.setLayoutParams(params);
// scale type
view.setScaleType(ScaleType.CENTER);
return view;
}
}
After much headache and heartache, I found the answer. I did not mention it previously or search for it specifically because I didn't think it was relevant, but I'm using Nuance's 360 SpeechAnywhere developer SDK to include speech recognition in my app. Hopefully I'm not breaking the terms of my SDK license by saying this:
Every "recognition enabled" activity is supposed to have a custom View as the root in order to embed speech recognition controls and functionality. It turns out that this custom View does not always refresh its children, unless you instruct it to via the custom View's synchronize() function. Long story short, I called the View's synchronize() method once my AsyncTask finished, onPostExecute() ran, and Bitmap was added to the activity.
In the AsynTask you work on UI changes.you can't do changes in the UI in background work.Use runOnUIThread always do computation on UI thread.It better depend on your easy of use.look at here.
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();
I am trying to use 'Universal Image Loader' to load images inside of my ListView. My code looks like that:
public View getView(int position, View convertView, ViewGroup parent)
if (convertView == null) {
convertView = mInflater.inflate(R.layout.offers_list_adapter, null);
holder = new ViewHolder();
holder.mIvImage = (ImageView) convertView
.findViewById(R.id.ivImage);
holder.mTxtName = (TextView) convertView.findViewById(R.id.txtName);
holder.mTxtCategoryName = (TextView) convertView
.findViewById(R.id.txtCategoryName);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
I have one rule:
If this item in my list is special one, I have to change my ImageView's params (e.g. special item has imageView bigger than normal).
So in my code I do that:
if (holder.isSpecial) {
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, 50);
layoutParams.gravity = Gravity.CENTER_HORIZONTAL;
holder.mIvImage.setLayoutParams(layoutParams);
}
After I change my params, I call the 'Universal Image Loader' library as usual:
imageLoader.displayImage(holder.url, holder.mIvImage);
But when the library execute in my UI thread to put the image in my ImageView, my ImageView is not at center and the size is wrong. My changes that I made because this item is special are not applied.
I have my own ImageDownloader and when I use it the ImageView load with the new params correctly (center and new size), but in many other points my own class is not so good as this library.
Anyone have any idea what might be happening?
Thanks in advance,
Cheers!
My 'Universal Image Loader' configuration:
DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheInMemory().cacheOnDisc()
.imageScaleType(ImageScaleType.IN_SAMPLE_POWER_OF_2)
.displayer(new RoundedBitmapDisplayer(0)).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
mContext)
.memoryCacheExtraOptions(480, 800)
.discCacheExtraOptions(480, 800, CompressFormat.JPEG, 75)
.threadPoolSize(3)
.threadPriority(Thread.NORM_PRIORITY - 1)
.denyCacheImageMultipleSizesInMemory()
.offOutOfMemoryHandling()
.memoryCache(new UsingFreqLimitedMemoryCache(2 * 1024 * 1024))
.discCache(new UnlimitedDiscCache(file))
.discCacheFileNameGenerator(new HashCodeFileNameGenerator())
.imageDownloader(
new URLConnectionImageDownloader(5 * 1000, 20 * 1000))
.defaultDisplayImageOptions(DisplayImageOptions.createSimple())
.enableLogging().defaultDisplayImageOptions(options).build();
imageLoader.init(config);
You have copy-pasted configuration from GitHub Readme. This config (on GitHub) just shows ALL possible options, but you SHOULD NOT call all of them.
You should look into example project (UniversalImageLoaderExample) to see right way of tuning and using UIL.