问题
I am parsing the xml file containing some names using the Async task and populating these names to the listview again via the main thread. But whats happening in my case is, when the Async task is still running, the main thread is already populating the names to the listview which is resulting in no items on the listview. Should i make the main thread wait until the Async task finish the job or is there any other way to solve this prob.? if yes how can i make the main thread wait when i don't know that how long the Async task might take to finish.?
回答1:
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
回答2:
If you want to complete the AsycTask then you can use .get()
method from AsyncTask. (Which will block the MainUiThread)
But I think the best approach is without blocking MainUiThread you have to start ProgressDialog on onPreExecute()
and after populating ListView in onPostExecute()
of AsyncTask finish the ProgressDialog in onPostExecute()
.
回答3:
You don't want to block your main thread and wait for the async task (this would defeat the purpose of the async task). Instead, the async task should trigger the update when it is finished in the onPostExecute
method.
You may also want to have a look at the more recent Loader
design.
回答4:
- First of all Main
thread in Android is the Dedicated UI thread
.
- What you need to do is to fill the List by parsing the xml with the names and then proceed to Displaying it on the ListView.
- You can use CoundDownLatch
from java.util.concurrent
package to fill in the data into the list before showing it on the ListView
.
- Use the method like await()
and countDown()
of CoundDownLatch
to do this.
回答5:
use AsyncTask.get() to wait until AsyncTask finish.
NOTE : this will stop execution of Main Thead until result not retrieved from AsyncTask
回答6:
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!
来源:https://stackoverflow.com/questions/14213642/how-to-make-the-main-thread-wait-when-i-dont-know-when-will-async-task-finish-t