1

When a background task returns a value how can it be accesses from another class. Just using this as example code, but what I want is the background task to do something and return a value.

protected String doInBackground(String... params) {
    publishProgress("Sleeping..."); // Calls onProgressUpdate()
    try {
       // Do your long operations here and return the result
       int time = Integer.parseInt(params[0]);    

       // Sleeping for given time period
       Thread.sleep(time);
       resp = "Slept for " + time + " milliseconds";
   } catch (InterruptedException e) {
       e.printStackTrace();
       resp = e.getMessage();
   } catch (Exception e) {
       e.printStackTrace();
       resp = e.getMessage();
   }

   **return resp;**
}
JDurstberger
  • 4,127
  • 8
  • 31
  • 68
Mark James
  • 481
  • 2
  • 6
  • 18
  • You may use AsyncTask for this purpose – Karthik CP Jan 25 '17 at 12:59
  • use interface for callbacks – Mohit Suthar Jan 25 '17 at 13:03
  • You will get better understanding here: http://stackoverflow.com/questions/9458258/return-a-value-from-asynctask-in-android – Karthik CP Jan 25 '17 at 13:06
  • Indeed you can handle the resut in `onPostExecute()` using an interface or calling a Callback which was a parameter of your AsyncTask. That is for a public AsyncTask class. If you make it a private class of your Activity you can simply call a function of your Activity in `onPostExecute() with the result as parameter.` – greenapps Jan 25 '17 at 13:07
  • Possible duplicate of [How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?](http://stackoverflow.com/questions/12575068/how-to-get-the-result-of-onpostexecute-to-main-activity-because-asynctask-is-a) – OneCricketeer Jan 25 '17 at 13:53

3 Answers3

2

For this you need to extend asynktask class like

extends AsyncTask<String, String, String>

@Override
protected void onPostExecute(String result) {
    //heare result is value you return from doInBackground() method 
    //this is work on UI thread
} 

Classs look like

public class AsyncTaskGetResult extends AsyncTask<String, String, String> {

    PrintListner mPrintListner ;      
    private AsyncTaskGetResult (PrintListner mPrintListner) {
        this.mPrintListner = mPrintListner;

    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }
    @Override
    protected String doInBackground(String... params) {
        return result;
    }

    @Override
    protected void onPostExecute(String result) {
    //heare result is value you return from doInBackground() method 
    //this is work on UI thread
    this.mPrintListner.getResult(result);
   }

}

public interface PrintListner {
    public void getResult(String receiptItem);
}

If you need to access it in another class you can write listner for that and implement in you activity

public class MyActivity extends Activity implements PrintListner{

       @Override
       public void getResult(String receiptItem){
        //Do whatever you want
       }
    }   

and call it like new AsyncTaskGetResult(this).execute(yourString);

Sushant Gosavi
  • 3,647
  • 3
  • 35
  • 55
0

AsyncTask:

public class YourBackgroundTask extends AsyncTask<String, Void, String> {
     private Callback callback;

     public YourBackgroundTask(Callback callback){
          this.callback = callback;
     }

     protected void doInBackground(String... strings) {
         // do what you have to do
         return result;
     }

     protected void onPostExecute(String result) {
          this.callback.onDone(result);
     }

     public Interface Callback{
          void onDone(String result);
     }
 }

and call it like this:

new YourBackgroundTask(yourCallback).execute(yourString);
Björn Kechel
  • 7,933
  • 3
  • 54
  • 57
0

You have a little misunderstanding. Background tasks do NOT return a value. They just do something. If you want to get a value out of some computation done in background you can make the background task so that when it finishes, it notifies some object about the resulting value.

The previous behavior can be done through the observer pattern in which an object is used to observe events from another object. In this case you want to define an observer (often called listener) and pass it to your background task.

Your listener interface may look like this:

interface ValueListener {
    public void onValueComputed(int computedValue);
}

Then an implementing class looks like this:

class ValueListenerImpl implements MyListener {
    @Override
    public void onValueComputed(int computedValue) {
        //do something...
    }
}

(or you can make an anonymous class)

Your background task:

class MyAsyncTask extends AsyncTask<Void, Void, Integer> {
    ValueListener listener;

    public MyAsyncTask(ValueListener valueListener) {
        this.listener = valueListener;
    }

    @Override
    public Integer doInBackground(Void.. params) {
        //do something...
        return someValue;
    }

    @Override
    public onPostExecute(Integer.. values) {
        listener.onValueComputed(values[0]);
    }
}

Finally, in your main thread you do:

    ...
    this.valueListener = new ValueListenerImpl();
    new MyAsyncTask(this.valueListener).execute();
    ...
Gonzalo
  • 3,674
  • 2
  • 26
  • 28