I am using a recyclerView to show images using asysnc task. I am getting the images from a web server. My code is
from onBindViewHolder methode I call
new ImageLoadTask(url, holder.imageView).execute();
My ImageLoader asysnc task is
public class ImageLoadTask extends AsyncTask<Void, Void, Bitmap> {
private String url;
private ImageView imageView;
ProgressDialog pDialog;
public ImageLoadTask(String url, ImageView imageView) {
this.url = url;
this.imageView = imageView;
}
@Override
protected Bitmap doInBackground(Void... params) {
try {
URL urlConnection = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlConnection
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
imageView.setImageBitmap(result);
}
}
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.
I tried passing the HttpURLConnection
from the adapter and checking if its not null and then calling disconnect
on this as shown before from onBindViewHolder
methode, but still it happens. I am using the
if (holder.urlConnection != null)
{
holder.urlConnection.disconnect();
try {
holder.urlConnection.getInputStream().close();
}
catch (Exception e) {
e.printStackTrace();
}
holder.urlConnection = null;
}
new ImageLoadTask(url, holder.imageView,holder.viewHolderActivity, holder.urlConnection).execute();
What can I do to cancel the image requests ?