Mark Tyers Mark Tyers - 1 month ago 11
Android Question

Efficiently download and use images in recyclerview

Currently I'm using this to download and display the images in my recyclerview:

private class RetrieveImageTask extends AsyncTask<URL,Void,Drawable>{
URL url;
InputStream inputStream;
protected Drawable doInBackground(URL... urls){
url = urls[0];
try {
inputStream = (InputStream)url.getContent();
} catch (IOException e) {
e.printStackTrace();
}
return Drawable.createFromStream(inputStream, null);
}
protected void onPostExecute(Drawable drawable) {

}
}


I then use this class in
onBindViewHolder
in my RecyclerViewAdapter:

@Override
public void onBindViewHolder(ItemViewHolder item, int i) {
try {
item.title.setText(aushangdata.getJSONObject(i).getString("title"));
item.desc.setText(aushangdata.getJSONObject(i).getString("text"));
item.tag.setText(aushangdata.getJSONObject(i).getString("category"));
item.link.setText(aushangdata.getJSONObject(i).getString("link"));
URL myUrl = new URL(aushangdata.getJSONObject(i).getString("image"));
RetrieveImageTask task = new RetrieveImageTask();
Drawable drawable = task.execute(myUrl).get();
item.thumb.setImageDrawable(drawable);
} catch (JSONException | IOException | InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}


This is obviously an extremely shitty solution, and it is very noticeable: when I open the fragment containing the recyclerview, I get a lag of up to 0.5 seconds, and when I scroll down fast it's also lagging because the images take up a lot of space on the cards.

My quesiton is: What is the most optimal way to download and display images in a
RecyclerView
?

Answer

You can use Glide: https://github.com/bumptech/glide

Also is so simple to use:

Glide.with(CONTEXT).load(URL or DRAWABLE).asBitmap().into(IMAGEVIEW);

Check the wiki for more options: https://github.com/bumptech/glide/wiki

In your code:

Glide.with(context).load(myUrl).asBitmap().into(item.thumb);

Hope it helps.