简体   繁体   中英

How to download images asynchronously from web server

My application screen looks similar to the image attached. I have multiple rows and each row has a Bitmap image, title and description field. All the information's are getting fetched from our supporting web-server in the form of XML. Now, I have used observer design pattern, which creates a separate thread for connecting to my remote server over HTTP, downloads and parse the XML. The XML includes the URL for image, title and description for each row.

在此输入图像描述

I have tried few approaches so far,

Approach 1:

  • Created a separate method (drawRow()), which takes care of putting the contents together by specifying the layout.
  • And, then using the method downloadImage(), I am trying to download the remote URL from the drawRow() method. But it sucks, as it downloads using the same thread and UI gets blocked.

Approach 2:

While searching for the above issue, I came across WebBitmapField in blackberry from coderholic.com .

And, then I am using the below code from my drawRow() method. As I understand the WebBitmapField, here is using observer design pattern and the image is downloading over thread other than UI thread. It works fine when I have limited number of rows like 5 or 10. But when I have more number of rows to be drawn it throws TooManyThreads exception, as it creates a new thread for each row.

I have got this link taskworker-thread-blackberry , but not much clear with how to achieve my requirement.

As I understand, in blackberry an application can create maximum of 16 number of threads. So, now I believe. I may need to create a thread pool specifying max size to 10.

Can anyone please help me to understand and implement the thread pooling for blackberry for my current problem?

Also, I appreciate anyone giving me any other best approach which will fit for my requirement.

Thanks in advance.

You have everything what you need. So:

  1. Create one TaskWorker for your application (use singelton)
  2. Implement Task class from TaskWorker - DownloadImageTask (simply put everything from Runnable.run() to Task.doTask() method)
  3. Instead of new thread creation in Util.getWebData() call TaskWorker.addTask()

There are probably more minor details but you could figure out how to finish it.

And I think it's better to have two method in Callback - success(byte[] data) and error(Throwable error) - to determine end result and escape converting images to String and back.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM