0

我正在考虑如何为 Activity 扩展布局,其内容将基于下载的解析 json 数据。

我想过使用AsyncTask 1)下载数据,2)解析它和3)更新UI,但是我使用的ListAdapter必须在主线程上,所以我不能把它放在AsyncTask的onPostExecute方法中。我有点困惑我应该采取什么方法。任何指针都非常感谢。

4

1 回答 1

0

像在这个例子中那样做:

 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
 protected Long doInBackground(URL... urls) {
     int count = urls.length;
     long totalSize = 0;
     for (int i = 0; i < count; i++) {
         totalSize += Downloader.downloadFile(urls[i]);
         publishProgress((int) ((i / (float) count) * 100));
         // Escape early if cancel() is called
         if (isCancelled()) break;
     }
     return totalSize;
 }

 protected void onProgressUpdate(Integer... progress) {
     setProgressPercent(progress[0]);
 }

 protected void onPostExecute(Long result) {
     showDialog("Downloaded " + result + " bytes");
 }

}

http://developer.android.com/reference/android/os/AsyncTask.html

在doInBackground(Params... para)中做任何你想做的事情。如果要更新 UI 或 ListAdapter。调用publishProgress(Params pa)它将调用onProgressUpdate(Integer.. progress)。在这个函数中,你可以更新 UI、更新数据或在主线程上做你想做的事。

希望能帮助到你。

于 2013-03-09T13:06:24.697 回答