Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retry AsyncTask

Tags:

android

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.

like image 603
skywa1ker Avatar asked Dec 27 '22 23:12

skywa1ker


1 Answers

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.

like image 166
CommonsWare Avatar answered Jun 16 '23 23:06

CommonsWare