1

I have a method which refreshes a list view by re-setting the adapter of the list view. The adapter downloads a thumbnail image for each list item when it is set.

I want to run this method called refreshListView() on a new thread so that the images get downloaded asynchronously but i'm aware that i can't update the UI on a separate thread.

What are the alternative ways to do this?

Thanks in advance.

EI756
  • 557
  • 1
  • 8
  • 19

5 Answers5

4

You could use an AsyncTask ( http://developer.android.com/reference/android/os/AsyncTask.html) or a Loader ( http://developer.android.com/guide/topics/fundamentals/loaders.html). I recommend using a loader as it seems to be always easier. Both were (among other things) designed for exactly this type of problem.

In order to use the Loader on any target platform less than 3.0, please refer to http://developer.android.com/sdk/compatibility-library.html.

Kurtis Nusbaum
  • 30,445
  • 13
  • 78
  • 102
2

Here is the entire code.

http://stackoverflow.com/questions/541966/android-how-do-i-do-a-lazy-load-of-images-in-listview/559781#559781

dcanh121
  • 4,665
  • 11
  • 37
  • 84
  • i got it working by setting the targetSDKVersion in the manifest to "2", the above code seems to load the images in a que. Is this the best way to load the images? Without setting the targetSDKversion to 2, only the placeholder image is displayed, the images don't seem to be downloaded – EI756 Oct 12 '11 at 08:17
1

AsyncTask also works for coordinating background jobs with UI element updates:

http://developer.android.com/reference/android/os/AsyncTask.html

kramimus
  • 35
  • 6
0

Hmm. If I understand right, you don't want to use the new adapter before the images have finished downloading? Where in the adapter is your image download code. Depending on that, you might only get to the download code once the adapter's views are being loaded/showed.

I usually download images first, in a background thread, and buffer them in a collection (of SoftReferences). Then, I have the adapter read from that collection when it loads.

pumuckl
  • 141
  • 1
  • 9
  • Basically, the adapter is called like : "LazyAdapter lazyAdapter = new LazyAdapter(this, imagesListStringArray, listText1, listText2);" So the images are feeded through to the adapter with a string array which was populated before creating and setting this adapter – EI756 Oct 11 '11 at 22:23
  • In your above LazyAdapter constructor, is imagesListStringArray an array of Strings? Is each String an url to an image that you want to download? – pumuckl Oct 11 '11 at 23:53
0

As previously mentioned, you can use AsyncTask which runs in another thread and can update the UI once the seperate thread has downloaded the thumbnails. Depending on how you want to implement it, you could also have the thumbnails update as they are downloaded by using the onProgressUpdate() method in AsyncTask. Otherwise use onPostExecute to reset the list adapter.

psoulos
  • 800
  • 8
  • 16