Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return value from async task in android

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?
       }
like image 964
Vignesh Avatar asked Apr 01 '13 07:04

Vignesh


2 Answers

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

} 
...
...
like image 157
klanm Avatar answered Sep 30 '22 00:09

klanm


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.

like image 35
user2230793 Avatar answered Sep 30 '22 00:09

user2230793