7

I created an async task to call my server to get data from DB.
I need to process the result returned from http server call.
From my activity i calling the async task in many places. so i cant use member variable to access the result. is there any way to do?

public Result CallServer(String params)
{

    try
    {
    new MainAynscTask().execute(params);
    }
    catch(Exception ex)
    {
        ex.printStackTrace();
    }
    return aResultM;//Need to get back the result

}  

    private class MainAynscTask extends AsyncTask<String, Void, Result> {


    @Override
    protected Result doInBackground(String... ParamsP) {    
        //calling server codes
        return aResultL;
    }       
    @Override
       protected void onPostExecute(Result result) {
          super.onPostExecute(result);
          //how i will pass this result where i called this task?
       }
Vignesh
  • 2,197
  • 7
  • 30
  • 40
  • 1
    Why not call a method that handles the value as shown in http://stackoverflow.com/a/9458274/1021640? – rarp Apr 01 '13 at 07:55
  • possibly duplicate of [Async](http://stackoverflow.com/questions/9458258/return-value-from-async-task-in-android) and [Async And](http://stackoverflow.com/questions/5457493/asynctask-return-value) – Usman Kurd Apr 01 '13 at 08:03
  • The right way is using [protocols](http://stackoverflow.com/a/26820666/2835520) – IgniteCoders Nov 08 '14 at 18:56

4 Answers4

15

Try to call the get() method of AsyncTask after you call the execute() method. This works for me

http://developer.android.com/reference/android/os/AsyncTask.html#get()

public Result CallServer(String params)
{
   try
   {
       MainAynscTask task = new MainAynscTask();
       task.execute(params);
       Result aResultM = task.get();  //Add this
   }
   catch(Exception ex)
   {
       ex.printStackTrace();
   }
   return aResultM;//Need to get back the result

} 
...
...
klanm
  • 2,968
  • 3
  • 18
  • 21
  • 2
    AsyncTask it's executed in other thread, if you try to do that, your main thread will be frizzed while the task don´t end getting the data from server, and the activity cannot handle user events when touch the screen. – IgniteCoders Nov 08 '14 at 18:54
  • 1
    I would not recommend using get as above, because assignment is synchronous. – JackAW Dec 18 '14 at 16:45
  • this will work but surely not a way to adopt. tis is good for educational projects but not in real time apps Reason : it makes the app laggy but holding on to the main thread which defies the whole purpose of using Async task – Antroid Jul 11 '17 at 19:53
3

There are two ways i can suggest -

  1. onPostExecute(Result) in AsyncTask. See http://developer.android.com/reference/android/os/AsyncTask.html#onPostExecute(Result)

  2. Send a broadcast with the result as an extra.

AsyncTask is an asynchronous task so it does NOT make sense to return the result to the caller. Rather handle the result in onPostExecute() like setting the value to TextView etc. Or send a broadcast so that some other listener can handle the result.

naXa stands with Ukraine
  • 30,969
  • 16
  • 175
  • 237
user2230793
  • 145
  • 6
  • O̶n̶e̶ ̶l̶i̶t̶t̶l̶e̶ ̶p̶o̶i̶n̶t̶:̶ ̶I̶f̶ ̶y̶o̶u̶ ̶a̶r̶e̶ ̶a̶c̶c̶e̶s̶s̶i̶n̶g̶ ̶`V̶i̶e̶w̶`s ̶f̶r̶o̶m̶ ̶`o̶n̶P̶o̶s̶t̶E̶x̶e̶c̶u̶t̶e̶(̶)̶` ̶(̶e̶.̶g̶.̶ ̶f̶r̶o̶m̶ ̶a̶n̶o̶t̶h̶e̶r̶ ̶t̶h̶r̶e̶a̶d̶)̶,̶ ̶d̶o̶ ̶i̶t̶ ̶i̶n̶s̶i̶d̶e̶ `A̶c̶t̶i̶v̶i̶t̶y̶.̶r̶u̶n̶O̶n̶U̶i̶T̶h̶r̶e̶a̶d̶(̶.̶.̶.̶)̶`;̶ - forget it, `onPostExecute()` is invoked on UI thread. – naXa stands with Ukraine Mar 02 '14 at 14:26
1

Here's how I got around this:

1) Create an interface class that defines a signature for a method to execute on completion:

public interface AsyncIfc {
    public void onComplete();
}

2) Set a property on your AsyncTask class to hold the delegate method:

    public AsyncIfc completionCode;

3) Trigger the delegate from onPostExecute() in the AsyncTask:

completionCode.onComplete();

4) From your calling logic, set the delegate property to an anonymous method:

task.completionCode = new AsyncIfc() {

    @Override
    public void onComplete() {
    // Any logic you want to happen after execution
    }
};
iDurocher
  • 846
  • 8
  • 7
0

When an asynchronous task is executed, the task goes through 4 steps:

  1. onPreExecute(), invoked on the UI thread before the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.

  2. doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.

  3. onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.

  4. onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter.

Use a handler

In your activity

    Handler mHandler = new Handler() { 
    @Override public void handleMessage(Message msg) { 
        String s=(String)msg.obj;
        tv.setText(s);
    }
};

//result is soap object in this case.
protected void onPostExecute(SoapObject result) {
    pd.dismiss();
    if(result != null) {
        Message msg=new Message();
        msg.obj=result.getProperty(0).toString();
        mHandler.sendMessage(msg);
    }
JJD
  • 47,369
  • 53
  • 194
  • 328
Raghunandan
  • 131,557
  • 25
  • 223
  • 252