Load images in listview only when they are about to display

661 Views Asked by At

I am working on making a music player and what i have done so far is that I created a song list in listview with their thumbnail images using metadata files. Now when i scroll my list it lags, that might be because of the image loading. I referred to Google Play Music App and what they have done is that they fetch album art at the time of scrolling so scrolling is smooth. Is there any way to implement that kind of functionality?

1

There are 1 best solutions below

2
On BEST ANSWER

You have to use lazy loading of images, so images will be downloaded in background.

public class DownloadImage extends AsyncTask<ImageView, Void, Bitmap> {

    ImageView imageView = null;

    @Override
    protected Bitmap doInBackground(ImageView... imageViews) {
        this.imageView = imageViews[0];
        return download_Image((String) imageView.getTag());
    }

    @Override
    protected void onPostExecute(Bitmap result) {
        imageView.setImageBitmap(result);
    }

    private Bitmap download_Image(String url) {
        try {
            URL ulrn = new URL(url);
            HttpURLConnection con = (HttpURLConnection) ulrn.openConnection();

            InputStream iS = con.getInputStream();
            Bitmap bmp = BitmapFactory.decodeStream(iS);
            return bmp;

        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

}

Make a call to this class in your adapter getview

imgThumbnail.setTag(<your image url>);
new DownloadImage().execute(imgThumbnail);