Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

}

like image 988
Leo Starić Avatar asked Feb 06 '16 09:02

Leo Starić


People also ask

Does glide cache images Android?

Glide enables effective loading and caching of images. You can load images from a variety of sources such as files URIs, Android resources, bitmaps, drawables, etc. Just use the load() method to receive images.

What is placeholder Glide?

Placeholder. Placeholders are Drawables that are shown while a request is in progress.


1 Answers

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

like image 86
Dhaval Parmar Avatar answered Oct 10 '22 02:10

Dhaval Parmar