如何从 asynctask 更新 ui [英] How to update ui from asynctask
问题描述
我已经看到很多关于如何执行此操作的示例,但我无法弄清楚如何在我的代码中实现它.
I've seen many examples of how to do this, but I can't figure how to implement it in my code.
我正在使用这个代码.
我已经更新了 url,所以它会收到一个带有动态数据的 json.我想要做的是使用此代码每 30 秒自动更新一次列表.
I am using this code.
I have updated the url, so it will receive a json with dynamic data.
What I'm trying to do is to automatically update the list every 30 secs with this code.
Handler handler = new Handler();
Runnable refresh = new Runnable() {
public void run() {
new GetContacts().execute();
handler.postDelayed(refresh, 30000);
}
};
刷新,调用url获取数据,但是UI没有更新.
It refreshes, and calls the url and gets the data, but the UI does not get updated.
感谢您为我指明正确方向的任何提示.
Thanks for any hints to point me in the right direction.
http://www.androidhive.info/2012/01/android-json-解析教程/
推荐答案
您在 AsyncTask 中有三个可与 UI 交互的受保护方法.
You have three protected methods in an AsyncTask that can interact with the UI.
onPreExecute()
- 运行之前
doInBackground()
- 运行
doInBackground()
完成
- 这仅在
doInBackground()
使用publishProgress()
调用它时运行
- this only runs when
doInBackground()
calls it withpublishProgress()
如果在您的情况下,任务运行的时间比您想要刷新的 30 秒长很多,您将需要使用
onProgressUpdate()
和publishProgress()
.否则onPostExecute()
应该可以解决问题.If in your case the Task runs for a lot longer than the 30 seconds you want to refresh you would want to make use of
onProgressUpdate()
andpublishProgress()
. OtherwiseonPostExecute()
should do the trick.有关如何实现它,请参阅官方文档.
See the official documentation for how to implement it.
这篇关于如何从 asynctask 更新 ui的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
- 运行之前