Starting an async task and make an action only when button clicked if result already available otherwise wait for result and then make action


I have this code to make an asynchronous call in the background, show a progress bar and start another activity when a button is clicked :

protected void onCreate(Bundle savedInstanceState) {
    // ....


    // call action here

public void onClick(View v) {
    if (v.getId() {
        new MyActivity.ActionTask().execute(action);

private void getAction(Action action) {
    try {
        Call<Action> getAction  api.callAction(model, action);
        Response<Action> response  getAction.execute();
        if (response.isSuccessful() && response.body() ! null) {
        } else {
            runOnUiThread(() -> showToast(R.string.error, this));
    } catch (IOException e) {
        runOnUiThread(() -> showToast(e.getMessage(), this));

private void startAction(Action action) {
    Intent intent  new Intent(this, ActionActivity.class);
    intent.putExtra("action", action);

private class ActionTask extends AsyncTask<Action, Void, Action> {
    protected Action doInBackground(Action... action) {
        return action[0];

I would like to start the asynchronous call as soon as the first activity is displayed in OnCreate to make it look faster for the user when he clicks on the button. So the asynchronous call starts as soon as the activity is created, then when the user clicks the button if the result is already available, the next activity starts, otherwise the progress bar is displayed until a result is available and once the result is ready the second activity starts. What’s the best way to do that?

[by Taboola]( Article Thumbnails:)[by Taboola]( Article Thumbnails:)

[Sponsored Links]( Article Thumbnails:)[Sponsored Links]( Article Thumbnails:)

[Promoted Links]( Article Thumbnails:)[Promoted Links]( Article Thumbnails:)

You May Like



]( “Timeline: How a couple fled Singapore after millions were lost in Tradenation luxury goods scam”)Timeline: How a couple fled Singapore after millions were lost in Tradenation luxury goods scamCNA



Dubai Hotels | Search Ads

]( “Dubai Hotels Might Actually Surprise You”)Dubai Hotels Might Actually Surprise YouDubai Hotels | Search Ads



Drain – Pipe Cleaning

]( “Tricks to Clean Your Drain Might Be Simpler Than Ever”)Tricks to Clean Your Drain Might Be Simpler Than EverDrain – Pipe CleaningLearn More



onCreate: start the task

AsyncTask: when the task finishes, check if the user has already clicked on the button. If so, start the next activity. If not, store the result of the task, or just a flag if no result needed.

onClick: Check if the task is done. If so, start the next activity. If not, show the progress indicator, and set a flag indicating the user has clicked the button.

Answered By – nasch

Leave a Comment