Issue
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 :
@Override
protected void onCreate(Bundle savedInstanceState) {
// ....
actionButton.setOnClickListener(this);
// call action here
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.actionButton) {
setProgressVisibility(VISIBLE);
new MyActivity.ActionTask().execute(action);
}
}
private void getAction(Action action) {
try {
Call<Action> getAction = api.callAction(model, action);
Response<Action> response = getAction.execute();
setProgressVisibility(INVISIBLE);
if (response.isSuccessful() && response.body() != null) {
startAction(response.body());
} else {
runOnUiThread(() -> showToast(R.string.error, this));
logger.error(getResources().getString(R.string.error));
}
} catch (IOException e) {
runOnUiThread(() -> showToast(e.getMessage(), this));
logger.error(e.getMessage());
setProgressVisibility(INVISIBLE);
}
}
private void startAction(Action action) {
Intent intent = new Intent(this, ActionActivity.class);
intent.putExtra("action", action);
startActivity(intent);
}
private class ActionTask extends AsyncTask<Action, Void, Action> {
@Override
protected Action doInBackground(Action... action) {
getAction(action[0]);
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?
Solution
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
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.