Android: Load/replace image from a thread
I have an activity that needs to parse an XML from web, then read in images according to the XML info. To speed things along, I created AsyncTask to do the parsing and image fetching. However, I cannot put the images into the activity from within the thread due to "cannot update view objec开发者_开发技巧ts from outside the view-creating thread..."
So I moved everything back to the main onCreate routine and it slows things down so much that it's not usable (UI not showing until everything is done (I guess when onCreate returns)) .
Any idea on how to tackle this problem (i.e. parsing/fetching using AsyncTask, then placing/updating images dynamically when each becomes available)? or where in the life-cycle should/can I update the UI?
Thanks in advance for all your help.
How are you using the AsyncTask? It's exactly for the purpose you mentioned: AsyncTask.doInBackground()
is running in a separate thread and can be used to do the time-consuming task (loading the bitmap), and AsyncTask.onPostExecute()
runs on the UI thread and can be used to perform quick operations that have to happen in the UI thread (i.e. replacing the bitmap in your View).
The async task was the right route. Use the async task to do the work in the background then use onpostexecute.
private class DownloadFilesTask extends AsyncTask<URL, Integer, imageview> {
protected imageView doInBackground(URL... urls) {
//parse and load
}
protected void onProgressUpdate(Integer... progress) {
//update progress if you have progress dialog
}
protected void onPostExecute(imageView result) {
//load image into view.
}
}
See Async task
Try this:
runOnUiThread(Runnable action)
//Runs the specified action on the UI thread.
I implemented this to update a ListView after getting data from the web and it works like a charm.
If you download the source from this tutorial ( to the bottom ), you can see an implementation of how this works. :-)
Edit: see this rar file: ( Eclipse source code of an upcoming tutorial :-) )
精彩评论