Image load fail using Picasso,Glide,Image Loader ,Universal Image Loader - android

i have creating Hindi video song application, but video thumb can't display in video list.
(Single image are loaded but multiple image array can't load.)
using multiple image loader library but doesn't load image:
Glide:
implementation 'com.github.bumptech.glide:glide:4.10.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.10.0'
Glide .with(viewHolder.icon_1.getContext())
.load(((AppModelicon) this.b.get(i)).getThumnail())
.into(viewHolder.icon_1) ;
Glide.with(MainActivity.this)
.load("https://img.youtube.com/vi/EEX_XM6SxmY/mqdefault.jpg")
.placeholder(R.drawable.ic_menu_camera)
.error(R.drawable.ic_menu_gallery)
.listener(new RequestListener<Drawable>() {
#Override
public boolean onLoadFailed(#Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
// log exception
Log.e("TAG", "Error loading image", e);
return false; // important to return false so the error placeholder can be placed
}
#Override
public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
return false;
}
})
.into(viewHolder.icon_1);
Picasso:
implementation 'com.squareup.picasso:picasso:2.+'
Picasso.get()
.load("https://img.youtube.com/vi/EEX_XM6SxmY/mqdefault.jpg")
.resize(50, 50)
.centerCrop()
.into(viewHolder.icon_1);
using request manager with glide :
RequestManager requestManager = Glide.with(a)
.applyDefaultRequestOptions(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.NONE))
.applyDefaultRequestOptions(RequestOptions.placeholderOf(R.drawable.ic_menu_camera));
requestManager
.applyDefaultRequestOptions(RequestOptions.skipMemoryCacheOf(true));
requestManager.load(pathToFile)
.into(viewHolder.icon_1);
background task method use :
String pathToFile = this.b.get(i).getThumnail();
DownloadImageWithURLTask downloadTask = new DownloadImageWithURLTask(viewHolder.icon_1);
downloadTask.execute(pathToFile);
public class DownloadImageWithURLTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageWithURLTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String pathToFile = urls[0];
Bitmap bitmap = null;
try {
InputStream in = new java.net.URL(pathToFile).openStream();
bitmap = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
Please help me how to solve this issue.

If you are load image in recyclerview, below code might help you out.
#Override
public void onBindViewHolder(final ViewHolder holder, int position)
{
Glide.with(this.context)
.load(urls.get(position))
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(holder.getImage());
}
for more full tutorial you can visit https://ledron.github.io/RecyclerView/

Dont pass MainActivity.this as context its always wrong..
try this
//in activity
Glide.with(this)
.load("https://pbs.twimg.com/profile_images/1123379185764917248/On9ZnfVh.png")
.into(imageView)
//in Fragments
Glide.with(view.context)
.load("url")
.into(imageView)
replace .load("url") and "imageView" with your own.

remove the below line in dependency
annotationProcessor 'com.github.bumptech.glide:compiler:4.10.0'

I am able to load your image url using glide:
implementation 'com.github.bumptech.glide:glide:4.9.0'
Glide.with(this#MainActivity)
.load("https://img.youtube.com/vi/EEX_XM6SxmY/mqdefault.jpg")
.placeholder(R.mipmap.ic_launcher)
.error(R.mipmap.ic_launcher)
.into(imageView)

Related

Displaying an Image Downloaded from the Internet as Annotation - Using Picasso

I cannot display the image downloaded from the Internet as annotation. I am implementing the following code and Picasso library. However, if I use a local image, it works. Thanks in advance for any help.
private void createAnnotation(int id, double lat, double lon, String caption, String photoUrl) {
SKAnnotation annotation = new SKAnnotation(id);
SKCoordinate coordinate = new SKCoordinate(lat, lon);
annotation.setLocation(coordinate);
annotation.setMininumZoomLevel(5);
SKAnnotationView annotationView = new SKAnnotationView();
View customView =
(LinearLayout) ((LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
R.layout.annotation_photo_and_text, null, false);
// If width and height of the view are not power of 2 the actual size of the image will be the next power of 2 of max(width,height).
//annotationView.setView(findViewById(R.id.customView));
TextView tvCaption = (TextView) customView.findViewById(R.id.annotation_photo_caption);
tvCaption.setText(caption);
ImageView ivPhoto = (ImageView) customView.findViewById(R.id.annotation_photo);
Picasso.with(getApplicationContext())
.load(photoUrl)
.resize(96, 96)
//.centerCrop()
.into(ivPhoto);
//ivPhoto.setImageResource(R.drawable.hurricanerain);
annotationView.setView(customView);
annotation.setAnnotationView(annotationView);
mapView.addAnnotation(annotation, SKAnimationSettings.ANIMATION_NONE);
}
Picasso loads images from the internet asynchronously. Try adding the image to the Annotation after it has been downloaded. You can use a Target to listen for the image download completion:
ImageView ivPhoto = (ImageView) customView.findViewById(R.id.annotation_photo);
Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
ivPhoto.setImageBitmap(bitmap);
annotationView.setView(customView);
annotation.setAnnotationView(annotationView);
mapView.addAnnotation(annotation, SKAnimationSettings.ANIMATION_NONE);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {}
};
ivPhoto.setTag(target);
Picasso.with(getApplicationContext())
.load(photoUrl)
.resize(96, 96)
.into(target);
try activity context in place of applicationcontext. It may work for you.
What if you try to load image using Target object, and then set downloaded bitmap to your ImageView?
Target target = new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
// loading of the bitmap was a success
// TODO do some action with the bitmap
ivPhoto.setImageBitmap(bitmap);
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
// loading of the bitmap failed
// TODO do some action/warning/error message
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
};
ivPhoto.setTag(target);
Picasso.with(getApplicationContext())
.load(photoUrl)
.resize(96, 96)
.into(target);

How can load the images with the Glide in ImageSwitcher

For creating image slide show , I want to use image switcher with timer .
I read this blog post it's very clear but it doesn't load images from network .
Now i want load images from network with Glide Library .
This is MainActivity :
public class MainActivity extends Activity {
private ImageSwitcher imageSwitcher;
private int[] gallery = { http://www.helloworld.com/image1.png, http://www.helloworld.com/image2.png, http://www.helloworld.com/image3.png,
http://www.helloworld.com/image4.png, };
private int position;
private static final Integer DURATION = 2500;
private Timer timer = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageSwitcher = (ImageSwitcher) findViewById(R.id.imageSwitcher);
imageSwitcher.setFactory(new ViewFactory() {
public View makeView() {
return new ImageView(MainActivity.this);
}
});
// Set animations
// https://danielme.com/2013/08/18/diseno-android-transiciones-entre-activities/
Animation fadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_in);
Animation fadeOut = AnimationUtils.loadAnimation(this, R.anim.fade_out);
imageSwitcher.setInAnimation(fadeIn);
imageSwitcher.setOutAnimation(fadeOut);
}
// ////////////////////BUTTONS
/**
* starts or restarts the slider
*
* #param button
*/
public void start(View button) {
if (timer != null) {
timer.cancel();
}
position = 0;
startSlider();
}
public void stop(View button) {
if (timer != null) {
timer.cancel();
timer = null;
}
}
public void startSlider() {
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
public void run() {
// avoid exception:
// "Only the original thread that created a view hierarchy can touch its views"
runOnUiThread(new Runnable() {
public void run() {
imageSwitcher.setImageResource(gallery[position]);
position++;
if (position == gallery.length) {
position = 0;
}
}
});
}
}, 0, DURATION);
}
// Stops the slider when the Activity is going into the background
#Override
protected void onPause() {
super.onPause();
if (timer != null) {
timer.cancel();
}
}
#Override
protected void onResume() {
super.onResume();
if (timer != null) {
startSlider();
}
}
}
I try to load images with glide but i don't know what should i do .
It's pretty easy to do, all you need is to load image using Glide to the ImageView that you can get from ImageSwitcher by method imageSwitcher.getCurrentView(). So you need to replace code inside run of your runOnUiThread method to the next code:
Glide.with(MainActivity.this)
.load(gallery[position])
.asBitmap()
.listener(new RequestListener<String, Bitmap>() {
#Override
public boolean onException(Exception e, String model, Target<Bitmap> target, boolean isFirstResource) {
return false;
}
#Override
public boolean onResourceReady(Bitmap resource, String model, Target<Bitmap> target, boolean isFromMemoryCache, boolean isFirstResource) {
position++;
if (position == gallery.length) {
position = 0;
}
imageSwitcher.setImageDrawable(new BitmapDrawable(getResources(), resource));
return true;
}
}).into((ImageView) imageSwitcher.getCurrentView());
Also don't forget to replace your image urls with appropriate urls (you now have there some dummy urls I see). So your gallery array should be a String[] array.
Don't forget also to include android.permission.INTERNET to your AndroidManifest.xml.
And finally you need to change android:layout_width property of your ImageSwitcher to match_parent in xml as Glide won't load image in it otherwise.
I think the approved answer is great but it is missing something key.
When they update the current image, this is basically just replacing the one in view. This means we might as well not use the ImageSwitcher at all. What we need to do, is update the next view and then show it. This will allow us to also see any transition effects we have added.
I have separated all this logic out within my own code to make it clean, but here it is in RAW form.
Setting up of your ImageSwitcher
Animation in = AnimationUtils.loadAnimation(this,android.R.anim.fade_in);
Animation out = AnimationUtils.loadAnimation(this,android.R.anim.fade_out);
imageSwitcher.setFactory(() -> {
ImageView imageView = new ImageView(getApplicationContext());
imageView.setLayoutParams(new FrameLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT,
FrameLayout.LayoutParams.MATCH_PARENT
));
return imageView;
});
imageSwitcher.setInAnimation(in);
imageSwitcher.setOutAnimation(out);
Call this to then update the next image
RequestOptions requestOptions = new
RequestOptions().diskCacheStrategy(DiskCacheStrategy.ALL);
Bitmap nextImage = getAppropriateImage();
GlideApp.with(this)
.load(nextImage)
.apply(requestOptions)
.into((ImageView) imageSwitcher.getNextView());
imageSwitcher.showNext();
I used the version of #rom4ek but I had some crash:
Fatal Exception: java.lang.RuntimeException
Canvas: trying to use a recycled bitmap android.graphics.Bitmap#7ad49c4
I think that this is because the drawable is not set into the same ImageView passed to into(...).
I changed it to use the "next view". We have to set the visibility from GONE to INVISIBLE for Glide.
imageSwitcher.getNextView().setVisibility(View.INVISIBLE);
Glide.with(...)
.load(url)
.listener(new RequestListener<String, Bitmap>() {
#Override
public boolean onException(Exception e, String model, Target<Drawable> target, boolean isFirstResource) {
return false;
}
#Override
public boolean onResourceReady(Drawable resource, String model, Target<Drawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
imageSwitcher.setImageDrawable(resource);
return true;
}
}).into((ImageView) imageSwitcher.getNextView());
Kotlin version:
it.nextView.visibility = View.INVISIBLE
Glide.with(...)
.load(url)
.listener(object : RequestListener<Drawable> {
override fun onLoadFailed(
e: GlideException?,
model: Any?,
target: Target<Drawable>?,
isFirstResource: Boolean
): Boolean {
return false
}
override fun onResourceReady(
resource: Drawable?,
model: Any?,
target: Target<Drawable>?,
dataSource: DataSource?,
isFirstResource: Boolean
): Boolean {
it.setImageDrawable(resource)
return true
}
})
.into(it.nextView as ImageView)

Images are not stored in the cache

I have this method, everything is worked perfectly but images always got from server and not load from cache! what happened ?
public static void makeImageRequest(String Unique_ID, final View parentView, final int id) {
String url = FILE_UPLOAD_FOLDER + Unique_ID + ".png";
final int defaultImageResId = R.drawable.user;
// Retrieves an image specified by the URL, displays it in the UI.
ImageCacheManager.getInstance().getImage(url, new ImageListener() {
#Override
public void onErrorResponse(VolleyError error) {
ImageView imageView = (ImageView) parentView.findViewById(id);
imageView.setImageResource(defaultImageResId);
}
#Override
public void onResponse(ImageContainer response, boolean isImmediate) {
if (response.getBitmap() != null) {
ImageView imageView = (ImageView) parentView.findViewById(id);
imageView.setImageBitmap(response.getBitmap());
} else if (defaultImageResId != 0) {
ImageView imageView = (ImageView) parentView.findViewById(id);
imageView.setImageResource(defaultImageResId);
}
}
});
}
Just use Picasso instead ImageCacheManager. Picasso is a powerful image downloading and caching library for Android. Images add much-needed context and visual flair to Android applications. Picasso allows for hassle-free image loading in your application—often in one line of code!
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
Here also can manage whether the image is successfully downloaded or it fails:
Picasso.with(context)
.load("http://i.imgur.com/DvpvklR.png")
.into(imageView, new Callback() {
#Override
public void onSuccess() {
// your code
}
#Override
public void onError() {
// your code
}
});
You should only add this line in your gradle:
compile 'com.squareup.picasso:picasso:2.5.2'
Hope it helps!

ImageView refresh with Glide

I have one ImageView and one image loaded in it with Glide:
Glide.with(ImageView.getContext())
.load(url)
.dontAnimate()
.placeholder(R.drawable.placeholder)
.signature(stringSignature)
.into(new GlideDrawableImageViewTarget(ImageView) {
#Override
public void onResourceReady(GlideDrawable drawable, GlideAnimation anim) {
super.onResourceReady(drawable, anim);
progressBar.setVisibility(View.GONE);
}
});
and when I want refresh the image, I run this same code again only with new signature. It's working perfectly, but when new loading is started, the visible image is gone immediately.
Question
Is possible keep the image in ImageView and replace it after new image is downloaded?
That's the expected behavior.
Each time you call .load(x), Glide call .clear() on the target and its associated request.
That's how Glide is able to handle its pool of Bitmaps, otherwise it would have no way to know when to recycle a Bitmap.
In order to implement this, you need to switch between two Targets, here is the core idea :
public <T> void loadNextImage(#NonNull T model,
#NonNull BitmapTransformation... transformations) {
//noinspection MagicNumber
int hash = model.hashCode() + 31 * Arrays.hashCode(transformations);
if (mLastLoadHash == hash) return;
Glide.with(mContext).load(model).asBitmap().transform(transformations).into(mCurrentTarget);
mLastLoadHash = hash;
}
Target mCurrentTarget;
private class DiaporamaViewTarget extends ViewTarget<ImageView, Bitmap> {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
mLoadedDrawable = new BitmapDrawable(mImageView.getResources(), resource);
// display the loaded image
mCurrentTarget = mPreviousTarget;
You can set loaded Drawable as placeholder in next loading, like this:
private Drawable placeholder = ContextCompat.getDrawable(ctx, R.drawable.placeholder);
public void loadImage(String url, ImageView imageView) {
Glide.with(imageView.getContext())
.load(url)
.placeholder(placeholder)
.into(new GlideDrawableImageViewTarget(imageView) {
#Override
public void onResourceReady(GlideDrawable drawable, GlideAnimation anim) {
super.onResourceReady(drawable, anim);
placeholder = drawable;
}
});
}

TouchImageView zoom scaled to frame with Picasso

I was using Universal Image Loader library to load a set of images and TouchImageView to allow zooming. I decided to replace Universal Image Loader with picasso. Everything worked fine except now the image zooms around a frame which is slightly bigger than the image.
#Override
public Object instantiateItem(ViewGroup view, int position) {
View imageLayout = inflater.inflate(R.layout.item_pager_image, view, false);
assert imageLayout != null;
TouchImageView imageView = (TouchImageView) imageLayout.findViewById(R.id.image);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
spinner.setVisibility(View.INVISIBLE);
Picasso.with(getApplicationContext()).setIndicatorsEnabled(false);
Picasso.with(getApplicationContext()).load(images[position]).into(imageView,new Callback() {
#Override
public void onSuccess() {
spinner.setVisibility(View.GONE);
}
#Override
public void onError() {
}
});
view.addView(imageLayout, 0);
return imageLayout;
I have been breaking my head over a few hours for this. Is this some issue TouchImageView has with Picasso? Any help would be appreciable. Thanks.
Mahram Foadi posted here a great solution that work for me too:
Picasso.with(context).load (someUri).into(new Target () {
#Override
public void onBitmapLoaded (final Bitmap bitmap,
final Picasso.LoadedFrom loadedFrom) {
someTouchImageView.setImageBitmap (bitmap);
}
#Override
public void onBitmapFailed (final Drawable drawable) {
Log.d(TAG, "Failed");
}
#Override
public void onPrepareLoad (final Drawable drawable) {
someTouchImageView.setImageDrawable (drawable);
}
});
Hope this helps other people like us to use TouchImageView with Picasso ;)
I figured out the whole issue somehow got fixed when I set the image width and height from wrap_content to fill_parent.
Here is if you are using Glide. Glide is faster in loading than picasso and cheaper in memory consuming
Glide.with(context).load(url).asBitmap().into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
someTouchImageView.setImageBitmap(resource);
}
});
For those who still run into this problem.
As inspired by a comment in this issue:
It's because needs View size and it's not available in TouchImageView implementation before bitmap is set
Load the image after the TouchImageView is created using .post().
Kotlin code:
touchImageView.post { // Load the image when the view is ready
Picasso.get()
.load(file)
.placeholder(R.drawable.image_placeholder)
.into(touchImageView)
}
Java code:
// Load the image when the view is ready
touchImageView.post(new Runnable() {
#Override
public void run() {
Picasso.get()
.load(file)
.placeholder(R.drawable.image_placeholder)
.into(touchImageView)
}
});

Categories

Resources