How to download images asynchronously from web server

谁说胖子不能爱 提交于 2020-01-01 16:48:07

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/10912647/how-to-download-images-asynchronously-from-web-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!