How to return value from async task in android

android, android-asynctask

Solution

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

} 
...
...

Problem

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? } ```

Original source

Related problems