So i am using recycler view to show images in a grid and downloading images from url as bitmaps using volley library.
public void onBindViewHolder(final TrendingAdapter.ViewHolder viewHolder, int i) {
ImageRequest request = new ImageRequest(url, new Response.Listener<Bitmap>() {
@Override
public void onResponse(Bitmap bitmap) {
if (bitmap != null) {
viewHolder.getmImageView().setImageBitmap(bitmap);
}
}
}, 0, 0, null,
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
}
});
AppController.getInstance().addToRequestQueue(request);
}
The problem is when i scroll and skip one or more views before the image is downloaded and that view is recycled the image donwnload reqest is not canceled on those intermediate view resulting in a flash of that/those image(s) before the actual image is loaded in that view.
So i thought of canceling those intermediate image requests using tags but cannot figure out how as it results in canceling of request in other parallel views as well!
Also when i use volley NetworkImageView (that handels such image canceling by itself) gives perfect results. But i need to get bitmap of every image to pick colors from it so i cannot use NetworkImageView.
Q) How do i cancel all pending volley image requsts (except the one it should be loading and without effecting other parallel views) on a specific imageview inflated using recyclerview?
You should use the
ImageLoader
class instead of directly adding a request to theRequestQueue
. That way, theget()
method, which is used to get images, will return an object of typeImageContainer
.Save this
ImageContainer
in theViewHolder
, and when a view gets recycled, simply call thecancelRequest()
method on the recycled image to cancel the request if it hasn't been performed yet.Take a look at the
NetworkImageView
's code. It works in a similar way.I solved the problem ! yaaeeye :D @Itai 's answer pointed me in the correct direction. I took a close look at NetworkImageView code and modified it according to my need. So i made a CustumNetworkImageView
Using CustomNetworkImageView :
SetmResponseObserver listens for if bitmap is loaded in ImageView and onSuccess is called if task is completed.. I also made a fuction that returns the bitmap on the image view and can be used as
I am new to android so please feel free to comment and correct me if i have done anything wrong. Yaaaeeyeee happy dayyy
}
I faced the same problem. I couldn't use
NetworkImageView
and image loader because I wanted to have a custom image request.So I found another way to cancel in flight request. I simply passed the image request in
ViewHolder
object fromonBindViewHolder
callback. InViewHolder
created a methodsetRequest(Request request)
.In this method check if the request is not null then call
request.cancel()
first otherwise just set the request into the holder.