4

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.?

suresh cheemalamudi
  • 6,190
  • 11
  • 49
  • 67
  • 1
    post your code , i think you should display a `ProgressDialog` while parsing xml and returning an `ArrayList` of items, and in your `onPostExecute()` method , set the Adapter to your `ListView` – Houcine Jan 08 '13 at 11:11

6 Answers6

6

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().

user370305
  • 108,599
  • 23
  • 164
  • 151
  • 1
    Just populate your ListView in `onPostExecute()` of AsyncTask with ProgressDialog. It gives best User Experience. – user370305 Jan 08 '13 at 11:15
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

Aditya Kushwaha
  • 839
  • 6
  • 12
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.

Henry
  • 42,982
  • 7
  • 68
  • 84
3

- 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.

Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
2

use AsyncTask.get() to wait until AsyncTask finish.

NOTE : this will stop execution of Main Thead until result not retrieved from AsyncTask

ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
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!