0

i want to get the value returns by asynctask after it's been completed. this is my code :

class asyncGet extends AsyncTask<Void, String, String> {
    Boolean goterror = false;
@Override
protected String doInBackground(Void... params) {
    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(url);
    HttpResponse response;
    try {
        request.setHeader("Cache-Control", "no-cache");
        request.setHeader("Cache-Control", "no-store");
        response = client.execute(request);
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        InputStream in = response.getEntity().getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder str = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            str.append(line);
        }
        in.close();
        return str.toString();
    } catch (Exception e) {
        goterror = true;
    }

    return null;
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    if (pDialog != null && pDialog.isShowing())
        pDialog.dismiss();

    if (result != null && goterror == false) {

}


}

The async is in another class , I want to show the result when it's done .

How can I return the result from the async ?

thanks

mohamad bagheri
  • 499
  • 1
  • 10
  • 25

4 Answers4

2

if you want to keep it asynchronous then it is already implemented in your code, use onPostExecute method, "result" contains the returned data.

Or if you want it to return data synchronously then use the extended asynctask like below:

        try {
          String result = new asyncGet().execute().get();
        } catch (InterruptedException e) {
            e.printStackTrace(); //handle it the way you like
        } catch (ExecutionException e) {
            e.printStackTrace();//handle it the way you like
        }
meghraj27
  • 111
  • 1
  • 4
1

You can create an interface, as follows:

public interface OnStringListener {

    void onStringCompleted(String s);

    void onStringError(String error);
}

and you will have to create the constructor of your AsyncTask with OnStringListener as parameter:

class asyncGet extends AsyncTask<Void, String, String> {
    Boolean goterror = false;

    private final OnStringListener mListener;

    public asyncGet(OnStringListener listener) {
        mListener = listener;
    } 

    //The rest of your code

And in your onPostExecute method you can return the String sending it by the method onStringCompleted:

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    if (pDialog != null && pDialog.isShowing())
        pDialog.dismiss();

    if (result != null && goterror == false) {

    }

    if (mListener != null) {
          mListener.onStringCompleted(result);
     } 
}

Of course, your methods onStringCompleted and onStringError have to be created in the Activity that you want to get the result of your AsyncTask. From there, you will be able to use your result in your other class.

I expect it will be helpful to you!

Francisco Romero
  • 12,787
  • 22
  • 92
  • 167
  • why to implement interface, when `onPostExecution` is directly available in calling activity? – Kishor Pawar Aug 23 '15 at 06:41
  • 1
    @KishorPawar asynctask is not in the same class as activity. Also using fragment without ui ( having asynctask ) and retaining it would be better to handle orientation change. You can attach fragment when its recreated and having callback implemented will help update ui easily – Raghunandan Aug 23 '15 at 06:44
  • @KishorPawar I just found this method some days ago and it worked for me. I don't know how to directly access to `onPostExecution` from another Activity, sorry. I just though it could be helpful. – Francisco Romero Aug 23 '15 at 06:44
  • @Raghunandan : exctly as document says, its `public abstract class` which has to be extended as the @mohamad has done. and the result from onPostExecute is directly available at calling activity/main thread – Kishor Pawar Aug 23 '15 at 06:47
  • @KishorPawar i would also suggest reading this http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html and the docs http://developer.android.com/guide/topics/resources/runtime-changes.html. Try your method while handling orientation change – Raghunandan Aug 23 '15 at 06:49
  • maybe @mohamad don't want to keep AsyncTask class code in Activity class to keep it more clean. So, I found Error404's solution very useful. Extra info- OnStringListener is actually a Callback interface, so better to use GetStringCallback for naming convention. – meghraj27 Aug 23 '15 at 06:58
  • The only reason to create an interface I can think of is, You can implement as many interface you want, but can extend only class. But ultimately you have to override interface method, which you anyways do for `doInBackground()`. So I would suggest extend `AsyncTask` in inner class. @Raghunandan: the orientation is irrespective of the implementation of asyncTask implementation. – Kishor Pawar Aug 23 '15 at 07:34
  • @KishorPawar *So I would suggest extend AsyncTask in inner class*. That's a bad idea. Handling orientation will be a problem. Any way its left to users. Good luck – Raghunandan Aug 23 '15 at 07:42
0

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

AsyncTask must be subclassed to be used. The subclass will override at least one method (doInBackground(Params...)), and most often will override a second one (onPostExecute(Result).)

So the philosophy is you override doInBackground and when the doInBackground finishes its task it passes the result to onPostExecute which result is available in your main thread.

Read the Full usage here

and if you still want synchronous execution call get() as explained by @meghraj27

Kishor Pawar
  • 3,386
  • 3
  • 28
  • 61
0

You can implement an interface to an Activity or class where you want the result of the AsynTask and trigger that interface from the AsynTask.

You can refer this post How to handle return value from AsyncTask

Community
  • 1
  • 1
Suhail Mehta
  • 5,514
  • 2
  • 23
  • 37