Android Glide: prevent white image if request fails

So, I'm just wondering if I can prevent Glide from loading a white (null) image in ImageView if the specified url is incorrect. I would like to save the image that I provide in XML if it cannot find the image (because it might be wrong due to user input).

I tried to return true in the listener, but I think it's just for handling the animation. 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);
}

}

+4
source share
1 answer

You can use .error(mDefaultBackground) --> Sets a Drawable to display if a load fails.to save the image. as below

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

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

from the documentation

+11
source

Source: https://habr.com/ru/post/1627548/


All Articles