skywa1ker skywa1ker - 6 months ago 35
Android Question

Retry AsyncTask

For example I have following AsyncTask:

private class MyAsyncTask extends AsyncTask<Void, Void, Boolean> {


@Override
protected Void doInBackground(Void... params) {
try {
//some code that may throws exception
return true;
} catch (IOException ex) {
return false;
}
}


@Override
protected void onPostExecute(Boolean param){
if (!param) {
AlertDialog.Builder builder = new AlertDialog.Builder(MyActivity.this);
builder.setMessage("Error");
builder.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//I want to retry MyAsyncTask here
}
});
builder.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
}


What is best practice to do this? I'm afraid of recursion this code.

Answer

You cannot strictly "retry" an instance of AsyncTask. You have to create a new instance and execute it, just as you did the first one. You should not encounter a recursion problem.