4

我正在使用异步任务解析包含一些名称的 xml 文件,并通过主线程再次将这些名称填充到列表视图中。但是在我的情况下发生的事情是,当异步任务仍在运行时,主线程已经将名称填充到列表视图中,这导致列表视图上没有任何项目。我应该让主线程等到异步任务完成工作还是有其他方法可以解决这个问题?如果是的话,当我不知道异步任务可能需要多长时间才能完成时,如何让主线程等待。?

4

6 回答 6

6

如果你想完成 AsycTask,那么你可以使用.get()AsyncTask 中的方法。(这将阻止 MainUiThread

但我认为最好的方法是在不阻塞MainUiThread的情况下,您必须启动ProgressDialogonPreExecute()并在AsyncTask中填充ListView后完成ProgressDialogonPostExecute()onPostExecute()

于 2013-01-08T11:12:19.643 回答
5

If you have used AsyncTask, then do the xml fetch in doInBackground() and update all your UI elements of the listview inside the onPostExecute(), this runs on the main UI thread and is automatically after doInBackground(). This way you dont have to explicitly make the UI thread wait

于 2013-01-08T11:27:52.930 回答
3

您不想阻塞主线程并等待异步任务(这会破坏异步任务的目的)。相反,异步任务应该在onPostExecute方法中完成时触发更新。

您可能还想看看最近的Loader设计。

于 2013-01-08T11:11:33.170 回答
3

-首先,AndroidMain中的线程是.Dedicated UI thread

-您需要做的是通过使用名称解析 xml 来填充列表,然后继续在 ListView 上显示它。

-您可以使用CoundDownLatchfrom java.util.concurrentpackage 将数据填写到列表中,然后再显示在ListView.

-使用await()countDown()of之类的方法CoundDownLatch来执行此操作。

于 2013-01-08T11:12:24.887 回答
2

使用AsyncTask.get() 等待 AsyncTask 完成。

注意:这将停止执行 Main Thead,直到未从 AsyncTask 检索到结果

于 2013-01-08T11:11:47.323 回答
0
String str_result= new RunInBackGround().execute().get();
Log.e("","show this");

RunInBackGround is your AsyncTasc class name. First will run async task and when it finished will show the bellow message!

于 2016-01-08T11:26:36.033 回答