Michael
Michael

Reputation: 375

Unable to get the result of AsyncTask

I have a AsyncTask class that is separate from the MainActivity.

protected void onPostExecute(ArrayList<String> result) {
          System.out.println("flag1");
          MainActivity.myLst=new ArrayList<String>();
          MainActivity.myLst=result;
}

then I have the following code in my MainActivity.

public void onCreate(Bundle savedInstanceState) {
    new AsyncTask().execute();
    System.out.println("flag2");
    System.out.println(myLst.size());
}

The program outputs the flag2 first and myLst.size is 0. If I negative to other activity and then come back to the main activity and myList.size has the correct size. I thought It should output everything and do the work in AsyncTask before the MainActivity.

Upvotes: 0

Views: 127

Answers (5)

malcolm the4
malcolm the4

Reputation: 357

You can just overwrite the onPostExecute() method inside the the code that calls the Asynctask.

For example,you have a AsyncTask called myAsyncTask. Then in your Activity do it like this:

new myAsyncTask() {

        @Override
        protected void onPostExecute( Result result ) {

            super.onPostExecute( result );
            // Do something with result here
        }
    }.execute(value1);

I had the same issue, I wanted to get the result inside a fragment.... Look at this topic

Upvotes: 1

Oyashiro
Oyashiro

Reputation: 505

You're creating an AsyncTask to do stuff asynchronously.

You're saying to another thread that it has work to do, but you're not waiting his result to do yours, that's why "flag2" is written before the other.

if you want to wait the result, you need to implement a callback in onPostExecute()

Upvotes: 3

nunofmendes
nunofmendes

Reputation: 3791

Like other have said and like I have said in the comments to your post, async means asynchronously, and in your case means it will probably finish the onCreate code before finishing the async task.

Either put the AsyncTask class inside your MainActivity (and call some method to print on PostExecute), or implement an Observing/Observer style in your activities to be able to notify your main activity that the async task is over.

Upvotes: 1

dcsohl
dcsohl

Reputation: 7396

Asynchronous means that it may be out of order. An asynchronous task often launches another thread that does the work in parallel, or in the background, to the main thread. You absolutely cannot assume that the asynchronous task will be completed when execute() returns!

Upvotes: 1

Geobits
Geobits

Reputation: 22342

The AsyncTask doesn't "do the work before MainActivity", that would defeat the purpose of an AsyncTask.

What you want to do is write up an interface to pass the value back to your Activity. This answer has a good example of that.

Upvotes: 3

Related Questions