0

In the following snippet:

public class ExternalClass {
    private int num = 1;

    public void backgroundTask() {
        new HttpTask().execute();
    }

    public int getNum() {
        return num;
    }

    private class HttpTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            //Do stuff...
        }

        @Override
        protected void onPostExecute(String result) {
            //Do stuff...
            ExternalClass.this.num = 2;
    }
}

In an Activity:

...
ExternalClass ec = new ExternalClass();
ec.backgroundTask();
int myNum = ec.getNum(); //NUM IS 1, NOT 2!!

What am I doing wrong? Everything works fine, my doInBackground() and onPostExecute() complete successfully but the field "num" don't change. I tried "num = 2" or even "this.num = 2" (I know is no correct, but...).

Stokres
  • 685
  • 2
  • 7
  • 12
  • 2
    `onPostExecute` will get fired after `doInBackground` so, calling `ec.getNum()` will never show you `myNum` as 2. Put log in `onPostExecute` and check about the value and you will see that it is 2. – hardartcore Feb 07 '13 at 13:25

1 Answers1

1

you will need to use AsyncTask.get() method to get result back in Main UI Thread from AsyncTask when doInBackground() execution complete

public void backgroundTask() {
        new HttpTask().execute().get();
    }

NOTE: when u call get() method of AsyncTask in Main UI thread this will stop exection of Main Thread . you will need to call backgroundTask() method from background Thread

ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
  • 1
    Thank you! (And thank @Android-Developer too). I think I understand how it works, now. Finally, I'm going to use this solution: http://stackoverflow.com/a/3291713/1369770 – Stokres Feb 07 '13 at 17:54