创建一个线程异步下载XML在UI元素的使用 [英] Creating a thread to asynchronously download xml for usage in UI elements
问题描述
我正在从一个位置抓住一个RSSFeed中,分析它,并显示在一个丰富的ListView的项目的应用程序。我找到了工作同步,但它挂在初始下载。我用ImageDownloader从谷歌博客异步抓取图像填充的ListView,但我如何去线程下载过程中,使显示更新等待,直到它通过RSS来适配器之前完成,并显示一个对话框,在初始下载?我完全新的线程和消息处理!
I'm making an application that grabs an RSSFeed from one location, parses it, and displays the items in a rich ListView. I've got it working synchronously, but it hangs on the initial download. I used ImageDownloader from the Google blog to asynchronously grab images to populate the ListView, but how do I go about threading the download process, making the display update wait until it's done before passing the RSS to the adapter, and display a dialog during the initial download? I'm totally new to threads and message handling!
下面是我的onCreate的code迄今:
Here's the code in my onCreate so far:
feedWait = new Handler() {
public void handleMessage(Message msg) {
Log.d(TAG, "made it to handler");
UpdateDisplay();
}
};
netThread.start();
和这里的主题:
private Thread netThread = new Thread() {
public void run() {
getFeed();
feedWait.handleMessage(new Message());
}
};
此抛出一个错误,说我有一个创建处理程序之前调用活套。prepare(),但如果我做的onCreate活套。prepare(),它只是失败。
This throws an error, saying I have to invoke Looper.prepare() before creating a handler, but if I do Looper.prepare() in onCreate, it just fails.
推荐答案
您应该使用的AsyncTask
这一点。例如,
You should use an AsyncTask
for this. For example,
private class GetFeedTask extends AsyncTask<Void,Void,Boolean> {
@Override
public Boolean doInBackground(Void... params) {
return getFeed();
}
private boolean getFeed() {
//return true if successful, false if not
}
@Override
public void onPostExecute(Boolean result) {
if(result) //got feed successfully
updateDisplay();
}
}
然后在你的的onCreate()
,只需拨打新GetFeedTask()执行();
请参阅http://developer.android.com/reference/android/os/AsyncTask.html对于文档。
这篇关于创建一个线程异步下载XML在UI元素的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!