Ok-Alex Ok-Alex - 4 months ago 25
Android Question

Can't stop/restart AsyncTask

Please help. I can restart the AsyncTask. App crashes every time, when second call to updatePoi().

Here is my code:


  1. I'm checking status of task and set cancel(true).

    public void updatePoi() {
    //new RefreshMapTask().execute();
    if (refreshMapTask.getStatus() == AsyncTask.Status.RUNNING ||
    refreshMapTask.getStatus() == AsyncTask.Status.PENDING) {
    refreshMapTask.cancel(true);
    }
    refreshMapTask.execute();
    }
    }

  2. Here is my AsyncTask. in doInBackground I wrote a break.

    private class RefreshMapTask extends AsyncTask<Void, Void, Void> {
    @Override
    protected void onPreExecute() {
    super.onPreExecute();
    getMapView().getOverlays().clear();
    myPoiOverlay.clear();
    exitOverlay.clear();
    }


    @Override
    protected Void doInBackground(Void... voids) {
    Application app = (Application)getApplication();
    Log.d(TAG, "exits count = " + app.getExits().size());

    GeoPoint pointToNavigate = null;

    for (Exit exit : app.getExits()) {

    for (Poi poi : exit.getPoi()) {
    if (isCancelled()){
    break;
    }
    //some code here
    }
    }

    //small code here
    return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
    getMapView().invalidate();
    }
    }



EDIT: added solution from comments into the question

public void updatePoi() {
//new RefreshMapTask().execute();
if (refreshMapTask.getStatus() == AsyncTask.Status.RUNNING ||
refreshMapTask.getStatus() == AsyncTask.Status.PENDING){
refreshMapTask.cancel(true);
refreshMapTask = new RefreshMapTask();
} else {
refreshMapTask = new RefreshMapTask();
}
refreshMapTask.execute();
}

Answer

An AsyncTask instance can only be called once. To make a second call, you need to create a new instance.