12

So I'm just interested if I could prevent Glide from loading a white (null) image into an ImageView if the url provided is wrong.. I'd like to keep the image that I provide in XML if it can't find the image (because it might be wrong due to user input).

I've tried returning true in the listener, but I guess that's just for animation handling. Many thanks!

 public static void loadImage(String url, Context c, ImageView target) {
    Glide.with(c).load(url).listener(new RequestListener<String, GlideDrawable>() {
        @Override
        public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
            e.printStackTrace();
            return true;
        }

        @Override
        public boolean onResourceReady(GlideDrawable resource, String model, Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
            return false;
        }
    }).into(target);
}

}

Leo Starić
  • 331
  • 1
  • 4
  • 16

3 Answers3

23

you can use .error(mDefaultBackground) --> Sets a Drawable to display if a load fails. to keep image. just like below

Drawable mDefaultBackground = getResources().getDrawable(R.drawable.default_background);

Glide.with(getActivity())
                .load(uri)
                .centerCrop()
                .error(mDefaultBackground).into(target);

from documentation

Dhaval Parmar
  • 18,812
  • 8
  • 82
  • 177
2

For newer versions of Glide, the syntax for setting an error image is as follows:

Glide.with(mContext)
     .load(url)
     .error(Glide.with(imgView).load(R.drawable.ic_image_when_url_fails))
     .into(imgView);
Isan Campos
  • 321
  • 2
  • 5
0

The simplest way which works perfectly in 2020 is

Glide.with(context)
      .load(image)
      .error(R.drawable.error_img) //in case of error this is displayed
      .into(imageView);
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
MrinmoyMk
  • 551
  • 7
  • 21