glide icon indicating copy to clipboard operation
glide copied to clipboard

How do I cancel Glide loading in RecyclerView's onViewDetachedFromWindow?

Open ghost opened this issue 11 years ago • 9 comments

I have a Recyclerview with a TextView in it. I used a GlideImageGetter to load images in the TextView and would like to cancel any pending image loading that is out of visibility (onViewDetachedFromWindow) due to scrolling vertically.

@Override
public void onViewDetachedFromWindow(ViewHolder holder) {
    //holder.contents refer to the TextView
    Glide.clear(holder.contents);
}

This is my current code, onViewDetachedFromWindow is called when the view is out of sight but Glide.clear() does not seems to work on the TextView.

How can it be done?

ghost avatar Jul 21 '15 15:07 ghost

Glide.clear(View) only works if you passed an object extending ViewTarget to into(...). Can you please share what is GlideImageGetter and/or how do you start the loads?

Blindly I would say to add a new field to the ViewHolder, Target<?> contentsTarget:

holder.contentsTarget = Glide.with.....load(...);

and then

@Override public void onViewDetachedFromWindow(ViewHolder holder) {
    Glide.clear(holder.contentsTarget);
    holder.contentsTarget = null;
}

But, if you're using a RecyclerView you shouldn't need to clear views manually. You just have to make sure you're using a ViewTarget which will ensure to clear the previous load to the same TextView when a new load is started for it, that is when the item is recycled and reused.

TWiStErRob avatar Jul 21 '15 16:07 TWiStErRob

This is how I do it. ViewHolder in my RecyclerView adapter. Initialize the TextView.

public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    TextView contents;
    public ViewHolder(final View itemView, int ViewType) {
        contents = (TextView) itemView.findViewById(R.id.contents);
    }
}

onBindViewHolder in the RecyclerView. Fetch the images from GlideImageGetter and set them in the TextView.

@Override
public void onBindViewHolder(final ThreadAdapter.ViewHolder holder, final int position) {
    //postList.get(position).content contains HTML with multiple <img> tags
    holder.contents.setText(Html.fromHtml(postList.get(position).content, new GlideImageGetter(context, holder.contents), null));

GlideImageGetter

public final class GlideImageGetter implements Html.ImageGetter, Drawable.Callback {

    private final Context mContext;

    private final TextView mTextView;

    public GlideImageGetter(Context context, TextView textView) {
        this.mContext = context;
        this.mTextView = textView;
        // save Drawable.Callback in TextView
        // and get back when finish fetching image form Internet
        mTextView.setTag(R.id.drawable_callback_tag, this);
    }

    @Override
    public Drawable getDrawable(String url) {
        final UrlDrawable urlDrawable = new UrlDrawable();

            System.out.println("Downloading from: " + url);
            Glide.with(mContext)
                    .load(url)
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(new ImageGetterViewTarget(mTextView, urlDrawable));

        return urlDrawable;

    }


    /**
     * Implements {@link Drawable.Callback} in order to
     * redraw the TextView which contains the animated GIFs.
     */
    @Override
    public void invalidateDrawable(Drawable who) {
        mTextView.invalidate();
    }

    @Override
    public void scheduleDrawable(Drawable who, Runnable what, long when) {

    }

    @Override
    public void unscheduleDrawable(Drawable who, Runnable what) {

    }

    private static class ImageGetterViewTarget extends ViewTarget<TextView, GlideDrawable> {

        private final UrlDrawable mDrawable;

        private ImageGetterViewTarget(TextView view, UrlDrawable drawable) {
        super(view);

        this.mDrawable = drawable;
    }

    @Override
    public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
         float width;
         float height;
         if (resource.getIntrinsicWidth() >= getView().getWidth()) {
             float downScale = (float) resource.getIntrinsicWidth() / getView().getWidth();
             width = (float) resource.getIntrinsicWidth() / (float) downScale;
             height = (float) resource.getIntrinsicHeight() / (float) downScale;
         } else {
             float multiplier = (float) getView().getWidth() / resource.getIntrinsicWidth();
             width = (float) resource.getIntrinsicWidth() * (float) multiplier;
             height = (float) resource.getIntrinsicHeight() * (float) multiplier;
         }
        Rect rect = new Rect(0, 0, Math.round(width), Math.round(height));

        resource.setBounds(rect);

        mDrawable.setBounds(rect);
        mDrawable.setDrawable(resource);


        if (resource.isAnimated()) {
            // set callback to drawable in order to
            // signal its container to be redrawn
            // to show the animated GIF
            mDrawable.setCallback((Drawable.Callback) getView().getTag(
                    R.id.drawable_callback_tag));
            resource.setLoopCount(GlideDrawable.LOOP_FOREVER);
            resource.start();
        }

        getView().setText(getView().getText());
        getView().invalidate();
    }

    /**
     * See https://github.com/bumptech/glide/issues/256
     *
     * @see com.bumptech.glide.GenericRequestBuilder#into(com.bumptech.glide.request.target.Target)
     */
    @Override
    public Request getRequest() {
        return null;
    }

    @Override
    public void setRequest(Request request) {

    }
}

UrlDrawable

final class UrlDrawable extends Drawable implements Drawable.Callback {

    private GlideDrawable mDrawable;

    @Override
    public void draw(Canvas canvas) {
        if (mDrawable != null) {
            mDrawable.draw(canvas);
        }
    }

    @Override
    public void setAlpha(int alpha) {
        if (mDrawable != null) {
            mDrawable.setAlpha(alpha);
        }
    }

    @Override
    public void setColorFilter(ColorFilter cf) {
        if (mDrawable != null) {
            mDrawable.setColorFilter(cf);
        }
    }

    @Override
    public int getOpacity() {
        if (mDrawable != null) {
            return mDrawable.getOpacity();
        }
        return 0;
     }

     public void setDrawable(GlideDrawable drawable) {
        if (this.mDrawable != null) {
            this.mDrawable.setCallback(null);
        }
        drawable.setCallback(this);
        this.mDrawable = drawable;
    }

    @Override
    public void invalidateDrawable(Drawable who) {
        if (getCallback() != null) {
            getCallback().invalidateDrawable(who);
        }
    }

    @Override
    public void scheduleDrawable(Drawable who, Runnable what, long when) {
        if (getCallback() != null) {
            getCallback().scheduleDrawable(who, what, when);
        }
    }

    @Override
    public void unscheduleDrawable(Drawable who, Runnable what) {
        if (getCallback() != null) {
            getCallback().unscheduleDrawable(who, what);
        }
    }
}

The problem is when I scroll through the Recyclerview quickly, the images are queued for download but the views are already out of sight. This causes the current visible view to not show any images until all previous images are downloaded.

ghost avatar Jul 22 '15 08:07 ghost

The problem is that Glide.clear only works if the Target it receives handles getRequest and setRequest according to contract. This is what Sam's was pointing out at https://github.com/bumptech/glide/issues/256#issuecomment-62585845.

I was trying to think about solutions in my head, some of them failed, but one may work which is similar to my blind guess above (I only included the differences, classes are for structural reference only, so you know where the new methods/fields go.):

class GlideImageGetter {
    private final Set<ImageGetterViewTarget> mTargets = new HashSet<>();

    GlideImageGetter() {
        clear(); // add before setTag
    }

    public static GlideImageGetter get(View view) {
        return (GlideImageGetter)view.getTag(R.id.drawable_callback_tag);
    }

    public void clear() {
        GlideImageGetter prev = get(mTextView);
        if (prev == null) return;
        for (ImageGetterViewTarget target : prev.mTargets) {
            Glide.clear(target);
        }
    }

    class ImageGetterViewTarget {
        void onResourceReady() {
            mDrawable.setCallback(get(getView())); // change getTag to get
        }

        private Request request; // overrides ViewTarget's behavior reverting to BaseTarget's
        @Override public void setRequest(Request request) { this.request = request; }
        @Override public Request getRequest() { return request; }
    }
}

The key here is the clear(), it is called when the same list item is being bound again. The previous GlideImageGetter holds the reference to all the images (their targets) in the HTML currently shown. Before setting the new HTML with a the brand new GlideImageGetter, clear them targets first. It is mimicking what Glide would do when a new load is started, except we're clearing the Target which implicitly clears the Request.

Note that it is safe to store the Request in a field, because no one knows about the target, but GlideImageGetter, in #256 the problem is that the default ViewTarget stores the request in View.tag essentially creating a constraint that you can only have one pending request for one View. Here ImageGetterViewTarget relaxes that by storing it inside the Target, letting Glide have multiple pending requests for the same View and then clear them in bulk.

TWiStErRob avatar Jul 22 '15 11:07 TWiStErRob

On, that's my fault in #256. I am rethink this.

Thinks to TWiStErRob, the similar idea:

    @Override
    public void onViewDetachedFromWindow(ViewHolder holder) {
        GlideImageGetter prev = (GlideImageGetter)holder.contents.getTag(R.id.view_targets_tag);
        if (prev == null) return;
        for (ImageGetterViewTarget target : prev.getTargets) {
            Glide.clear(target);
        }
    }

floating-cat avatar Jul 22 '15 12:07 floating-cat

Good News! Your solution might just be working! I scrolled over 1000 images to check if the last image will load and it does! I'll test it more! Thanks @TWiStErRob !

Here's the full code for everyone in case you are interested! GlideImageGetter was originally from @floating-cat ! Thanks to you too!

public final class GlideImageGetter implements Html.ImageGetter, Drawable.Callback {

    private final Context mContext;

    private final TextView mTextView;

    private final Set<ImageGetterViewTarget> mTargets;

    public GlideImageGetter(Context context, TextView textView) {
        this.mContext = context;
        this.mTextView = textView;

        clear(); // Cancel all previous request
        mTargets = new HashSet<>();
        mTextView.setTag(R.id.drawable_callback_tag, this);
    }

    public static GlideImageGetter get(View view) {
        return (GlideImageGetter)view.getTag(R.id.drawable_callback_tag);
    }

    public void clear() {
        GlideImageGetter prev = get(mTextView);
        if (prev == null) return;

        for (ImageGetterViewTarget target : prev.mTargets) {
            System.out.println("Cleared!");
            Glide.clear(target);
        }
    }
    @Override
    public Drawable getDrawable(String url) {
        final UrlDrawable urlDrawable = new UrlDrawable();

        System.out.println("Downloading from: " + url);
        Glide.with(mContext)
                .load(url)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .into(new ImageGetterViewTarget(mTextView, urlDrawable));

        return urlDrawable;
    }

    @Override
    public void invalidateDrawable(Drawable who) {
        mTextView.invalidate();
    }

    @Override
    public void scheduleDrawable(Drawable who, Runnable what, long when) {

    }

    @Override
    public void unscheduleDrawable(Drawable who, Runnable what) {

    }

    private static class ImageGetterViewTarget extends ViewTarget<TextView, GlideDrawable> {

        private final UrlDrawable mDrawable;
        private Request request;

        private ImageGetterViewTarget(TextView view, UrlDrawable drawable) {
            super(view);
            mTargets.add(this); // Add ViewTarget into Set
            this.mDrawable = drawable;
        }

        @Override
        public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) {
             // Resize images - Scale image proportionally to fit TextView width
             float width;
             float height;
             if (resource.getIntrinsicWidth() >= getView().getWidth()) {
                 float downScale = (float) resource.getIntrinsicWidth() / getView().getWidth();
                 width = (float) resource.getIntrinsicWidth() / (float) downScale;
                 height = (float) resource.getIntrinsicHeight() / (float) downScale;
             } else {
                 float multiplier = (float) getView().getWidth() / resource.getIntrinsicWidth();
                 width = (float) resource.getIntrinsicWidth() * (float) multiplier;
                 height = (float) resource.getIntrinsicHeight() * (float) multiplier;
             }
            Rect rect = new Rect(0, 0, Math.round(width), Math.round(height));

            resource.setBounds(rect);

            mDrawable.setBounds(rect);
            mDrawable.setDrawable(resource);

            if (resource.isAnimated()) {
                // set callback to drawable in order to
                // signal its container to be redrawn
                // to show the animated GIF

                mDrawable.setCallback(get(getView()));    
                resource.setLoopCount(GlideDrawable.LOOP_FOREVER);
                resource.start();
            }

            getView().setText(getView().getText());
            getView().invalidate();
        }

        @Override
        public Request getRequest() {
            return request;
        }

        @Override
        public void setRequest(Request request) {
            this.request = request;
        }
    }
}

ghost avatar Jul 22 '15 14:07 ghost

I used the Glide-Volley integration and when scroll through a hell lot of images in the recyclerview, the app will crash due to OOM.

I added the trimMemory() call in the onViewRecycled

@Override
public void onViewRecycled(ViewHolder holder) {
    super.onViewRecycled(holder);
    Glide.get(context).trimMemory(ComponentCallbacks2.TRIM_MEMORY_MODERATE);
}

The out of memory problem was not seen after this but I was wondering if this is the right way to solve it.

ghost avatar Jul 23 '15 07:07 ghost

Most likely not, take a heap dump jjust before an OOM and check who keeps references to large objects, like Bitmaps.

TWiStErRob avatar Jul 23 '15 09:07 TWiStErRob

Let us know if there are further questions, thanks again @TWiStErRob!

sjudd avatar Aug 04 '15 14:08 sjudd

https://bumptech.github.io/glide/int/recyclerview.html

tigran-babajanyan avatar Jan 25 '19 10:01 tigran-babajanyan