Leo Starić
Leo Starić

Reputation: 331

Android Glide: prevent white image if the request fails

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);
}

}

Upvotes: 12

Views: 14203

Answers (3)

MrinmoyMk
MrinmoyMk

Reputation: 603

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);

Upvotes: 0

Isan Campos
Isan Campos

Reputation: 371

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);

Upvotes: 2

Dhaval Parmar
Dhaval Parmar

Reputation: 18978

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

Upvotes: 23

Related Questions