Issue
I am trying to stop an AsyncTask in Android. In doInBackground it runs through an IP - Address list and tries to ping all of them.
Furthermore, when executing the AsyncTask a ProgressDialog opens which you can cancel. Calling this cancel - text calls the onCancelled method in AsyncTask. So, this method is being called, but it seems as if it is never stopped because when I hit the button Find again, I always get the following error message:
java.lang.IllegalStateException: Cannot execute task: the task has already been executed (a task can be executed only once)
Here is my code:
private Settings.HostWorker hostWorker;
private void initComponents() {
hostWorker = new Settings.HostWorker();
progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if(!hostWorker.isCancelled()) {
hostWorker.cancel(true);
}
}
});
}
findServerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
if(findServerButton.isClickable()) {
progressDialog.show();
hostWorker.execute();
findServerButton.setClickable(false);
}
}
});
private class HostWorker extends AsyncTask<Integer, String, Void> {
@Override
protected Void doInBackground(Integer... params) {
try {
for (int i = 0; i <= 255; i++) {
String ip = createHostsList(i);
if (ip != null) {
publishProgress(ip);
}
if(isCancelled())
{
break;
}
}
} catch (Exception e) {
MyAlertDialog myAlertDialog = new MyAlertDialog(getBaseContext(), "Error in Settings - doInBackground: " + e.getMessage());
myAlertDialog.showAlertDialog();
}
return null;
}
protected void onProgressUpdate(String... values) {
hostsOnline.add(values[0]);
settingsCustomArrayAdapter.notifyDataSetChanged();
}
protected void onCancelled(){
findServerButton.setClickable(true);
}
@Override
protected void onPostExecute(Void aVoid)
{
super.onPostExecute(aVoid);
}
}
Solution
The error
Cannot execute task: the task has already been executed (a task can be executed only once)
suggests that you need to create a new HostWorker
instance each time you want to run the task. You could achieve this by removing the line
hostWorker = new Settings.HostWorker();
from initComponents
and instead adding it into your findServerButton
OnClickListener
like so:
findServerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
if(findServerButton.isClickable()) {
progressDialog.show();
hostworker = new Settings.HostWorker(); // Line added here.
hostWorker.execute();
findServerButton.setClickable(false);
}
}
});
Answered By - stkent
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.