Naftuli Kay
Naftuli Kay

Reputation: 91630

Load images over HTTP for list items

I need to load images to go in each row in a ListLayout. Currently, I have an ExecutorService that essentially does the following:

pubilc View getView(...) {
    ...
    this.executor.execute(new Runnable() {
        public void run() {
            // load image over HTTP
            image.post(new Runnable() {
                public void run() {
                    image.setImageBitmap(loadedBitmap);
                }
            });
        }
    });
}

Unfortunately, this really doesn't work too well, my images are constantly reloading with the wrong values, and my application crashes when trying to scroll. What is the recommended method of doing this?


EDIT

I have updated my code to use AsyncTask implementations for loading images (makes so much more sense and so much less headache), but how should I sequence my tasks in my adapter? If I need to be only running one task at a time, that's fine, but I essentially need a list that I can add to and invalidate at will. What's also weird is that when I first start my application, the images load, but more often than not, they initially load in the wrong places, then reload a few times until everything looks okay. Weird. Is there a suggested way of doing this?

Upvotes: 0

Views: 342

Answers (2)

DynamicMind
DynamicMind

Reputation: 4258

Use the below method for loading image from internet.

Resources res ; public static Bitmap LoadImage(String URL, BitmapFactory.Options options) { Bitmap bitmap = null;

    InputStream in = null;
    try {
        in = OpenHttpConnection(URL);
        // options.inSampleSize = 8;
        if (in == null) {
            bitmap = BitmapFactory.decodeResource(TennisAppActivity.mContext.getResources(),
                    R.drawable.profileplaceholder);
            return bitmap;
        } else {
            options.inSampleSize = 5;
            bitmap = BitmapFactory.decodeStream(in, null, options);
        }
        in.close();
    } catch (IOException e1) {
    }
    return bitmap;
}

Then calling look lick this

final BitmapFactory.Options bmOptions; bmOptions = new BitmapFactory.Options(); LoadImage(ImageUrl,bmOptions);

I hope this is help.

Upvotes: 0

Matthew
Matthew

Reputation: 44919

I think the way to do this is to have a class to maintain a queue of image urls to download and a (variable) number of AsyncTasks to service the queue.

The class should be able to:

  • add new urls to the queue, which are serviced by AsyncTasks as they become available
  • cancel tasks for urls that scroll out of view in the ListView (you can detect this from the convertView parameter in getView())
  • notifies your ListView via a callback that an image for a certain url has loaded, allowing it to find and invalidate (refresh) that view

Upvotes: 1

Related Questions