3

I have an application with the following workflow :

Main activity where the user types his research keywords -> Click on the "search" button -> Starting an AsyncTask making a query on a webservice (query handled within the doInBackground method) -> Creation of a new activity.

Now I want to display the webservice result within this new activity. How can I do ? I know I should to use "onPostExecute" but the AyncTask object has not any access to this new Activity from the "onPostExecute" method. Any clues ?

Thank you !

Simon
  • 1,679
  • 4
  • 21
  • 37

1 Answers1

1

How to access to GUI elements from OnPostExecute

Make a activity and get the view in onCreate(bundle) and Define a AsyncTask as inner class.

public class MainActivity extends Activity
{ 
    TextView textView;
    public void onCreate(Bundle bundle){
         ....
        textView = (TextView)findViewById(R.id.textview);
    }

Declare the AsyncTask inside this class.

   private class UpdateUiAsyncTask extends AsyncTask<Void, Void, Void>{
      ........
      .....
     protected void onPostExecute(String result) {
      textView.setText(result);
     }
  }
}
Ajay S
  • 48,003
  • 27
  • 91
  • 111
  • 1
    This solution can cause memory leaks. Please check this: https://stackoverflow.com/questions/12252654/android-how-to-update-an-ui-from-asynctask-if-asynctask-is-in-a-separate-class – Martin Pfeffer Oct 06 '17 at 08:50
  • 1
    you should do the same thing as you do for context which is to pass the view in a WeakReference – AouledIssa Feb 19 '19 at 16:12