开发者

Asynctask in listactivity

I have a listactivity and each row has a di开发者_Python百科fferent image that i load from the web and some text. I'd like to implement asynctask so the images would load on the background. I've searched many tutorials but haven't found none that use different images per row. The problem is the method doInBackground that is supposed to load the images from the internet. But since they are all different and they depend on its row, how can the thread load them?

Global variables: Bitmap bm; BitmapFactory.Options bmOptions;

In my getView method, I have

ImageView img = (ImageView) v.findViewById(R.id.icon); if (img!=null){ bm = LoadImage(o.getLink(), bmOptions); img.setImageBitmap(bm); }

along with the text load... this img should be load on the doInBackground method, but then I'd have no access to the o (of type User) object that I know because getView gives me the position.

Does anyone have any idea on how to solve this problem?

Thanks, Rita


There are two ways you can do this: the easy way or the boring way.

If you can add extra dependencies, then I would strongly recommend you take the easy route and use GreedDroid. You can use the item framework they have in there or use the AsyncImageView. Personally I'd use the latter.

The boring way, on the other hand, would be to break out the HttpClient and download the image manually, then use BitmapFactory.decodeStream method to create a Bitmap.

The downloading needs to happen away from the UI thread, so it may feel natural to use an AsyncTask to run it all, and the use a Handler to actually poke the Bitmap into the ImageView (being careful not to set the Bitmap on a view which has already been recycled).

Unfortunately, on many implementations, the ExecutorService that runs the AsyncTasks are limited to using one Thread. This gives an unfortunate feel to the List where the images load one by one, instead of the as-many-as-possible-all-at-once feel to it you may be expecting.

In that case, you'll probably be wanting to (essentially) roll your own AsyncTask.

I'm not a massive fan of AsyncTasks, as you can tell.

The above is such a common task, and such an annoying thing to get right, I'd very much recommend using someone else's library.


I believe you will need to write your own List Adapter so that as more and more list items are displayed (by scrolling down for example), the adapter creates more AsyncTasks and displays the images once they have been fetched.

http://developer.android.com/reference/android/widget/ListAdapter.html


This is where images will be downloaded using async task just have look http://developer.android.com/resources/articles/painless-threading.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜