Android AsyncTask get result after finsih execute

androidandroid-asynctask

I have a class that extends AsyncTask

public class MyClass extends AsyncTask<Void, Void, Void> {
    private String response;

    public String getResponse(){
        return response;
    }

    @Override
    protected Void doInBackground(Void... arg0) {
         /* code */
         return null;
    }
    @Override
    protected void onPostExecute(Void result) {
        response = aString;
        super.onPostExecute(result);
    }
}

In other activity, I create an instance of MyClass

 MyClass c = new MyClass();
 c.execute();
 response = c.getResponse();
 Toast.makeText(getApplicationContext(), "response = " + response, Toast.LENGTH_LONG).show();

However I got null on the response variable, maybe because the Toast was executed before the task finish. Could you give me the right way so I can get the result after the task finish?

Best Answer

You don't need a class field for the result. The AsyncTask<Params, Progress, Result> delivers everything you need.

So you want to have a String back from the Task. In order to accomplish that you have to change the Result to String. Basically like this:

public class MyClass extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... arg0) {
         /* do background stuff to get the String */
         return string; // the one you got from somewhere
    }
}

You also have to wait for the computation by calling the method get().

String response = new MyClass().execute().get();
Toast.makeText(getApplicationContext(), "response = " + response, Toast.LENGTH_LONG).show();

Read more about AsyncTask#get here