2

In android, is it possible to get return values from functions that are run in execute?

Calling file

Connector connector  = new Connector();
connector.execute("login", ipPop.getText().toString(), username.getText().toString(), password.getText().toString());

Function file

public class Connector extends AsyncTask<String,Void,Void>{
    @Override
    protected Void doInBackground(String... voids) {
        return false;
    }
}
333
  • 345
  • 2
  • 7
SeanLink11
  • 23
  • 1
  • 8

1 Answers1

1

You are using AsyncTask in Android. When your class extends it, you can override 3 more methods. Here you can override onPostExecute which is passed with data from doInBackground return. Since onPostExecute runs on UI thread you can update UI from there like cancelling progressbar.

@Override
protected void onPostExecute(String result) {
   // "result" is data return from doInBackground method
   // execution of result of Long time consuming operation
       
}

Refer this sample for your understanding

As per latest android version, AsyncTask is deprecated avoid using it. Check alternatives

333
  • 345
  • 2
  • 7
  • @303 So, I understand from what you're saying is that using the alternatives should be better, but because I'm short on time, I think I should focus on using AsyncTask first then switching to the alternatives later on during the maintenance period of the project. May I ask, does it means that I can return the values back to the function that called `execute` using `onPostExecute`? – SeanLink11 Oct 25 '20 at 09:42
  • ok. No through AsyncTask directly you can't. What you want achieve? you must be trying to login, rght? Once you start AsyncTask based on success or failure, handle UI changes in `onPostExecute` method. If you are using AsyncTask to make API call, I will suggest using library like `Retrofit`. it will be much simpler. – 333 Oct 25 '20 at 09:47
  • Oh... I see, I think I get it, thanks for your help – SeanLink11 Oct 25 '20 at 09:48