1

I am trying to add this code to my doInBackGround so I can catch a flag that is being set when the user presses the back button

protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }

This my doInBackGround and the code I use to set the flag for the asynctask to be canceled

@Override
public void onBackPressed() 
{              
    /** If user Pressed BackButton While Running Asynctask
        this will close the ASynctask.
     */
    if (mTask != null && mTask.getStatus() != AsyncTask.Status.FINISHED)
    {
        mTask.cancel(true);
    }          
    super.onBackPressed();
    finish();
}


@Override
protected void onDestroy() {
    // TODO Auto-generated method stub


/** If Activity is Destroyed While Running Asynctask
        this will close the ASynctask.   */

 if (mTask != null && mTask.getStatus() != AsyncTask.Status.FINISHED)
 {
    mTask.cancel(true);
  }  

    super.onDestroy();

}

@Override
protected void onPause() {
    // TODO Auto-generated method stub


 if (pDialog != null)
 {
     if(pDialog.isShowing())
     {
         pDialog.dismiss();
     }
        super.onPause();

  }  

}

class LoadAllData extends AsyncTask<String, String, String> {



    protected String doInBackground(String... args) {  

        try {
            Intent in = getIntent();
            String searchTerm = in.getStringExtra("TAG_SEARCH");
            String query = URLEncoder.encode(searchTerm, "utf-8");
            String URL = "example.com";
            JSONParsser jParser = new JSONParsser();
            JSONObject json = jParser.readJSONFeed(URL);
            try {

                JSONArray questions = json.getJSONObject("all").getJSONArray("questions");

                for(int i = 0; i < questions.length(); i++) {
                    JSONObject question = questions.getJSONObject(i);


                String Subject = question.getString(TAG_QUESTION_SUBJECT);
                String ChosenAnswer = question.getString(TAG_QUESTION_CHOSENANSWER);
                String Content = question.getString(TAG_QUESTION_CONTENT);

The problem comes when I try to translate isCancelled into my asynctask. I get an error under Downloader that says "Downloader cannot be resolved" I also get one under publishProgress that says "The method publishProgress(String...) in the type AsyncTask is not applicable for the argument (int)" I'm jus tasking is somebody can help put the isCancelled into my AsyncTask. I have also done my research and seen that there are more than one way to use isCancelled in your code. I have realized that dealing with isCancelled can really be a hassle for somebody new to it.

BC2
  • 892
  • 1
  • 7
  • 23
Inman Douche
  • 139
  • 3
  • 8

2 Answers2

1

1) To resolve error one make Downloader a public static data variable of the class.
2) Please make sure

private class DownloadFilesTask extends AsyncTask<URL, Integer, Long>

is the class declaration

After you called cancel() isCancelled() will return true, and after your doInBackground returned onCancelled is executed instead of onPostExecute. The Parameter will issue an interrupt on the background thread, so your long-time operations are closed. However, I'd assume you catch that somewhere?

Hope this Helps..:).. If it doesnt solve the error..Please post logcat details

From SDK:

Cancelling a task

A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true. After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns. To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]), if possible (inside a loop for instance.)

Also please use super.onpause() etc at the begining of the function block

Refer this:- link

Community
  • 1
  • 1
Augustus Francis
  • 2,694
  • 4
  • 22
  • 32
  • Is `abort` a reasonable method to use here because some of my friends suggested this to me and also after I call it I need to catch it with an `Exception` – Inman Douche Sep 18 '13 at 23:02
  • See my updated answer.. 'pDialog.setOnCancelListener(new DialogInterface.OnCancelListener(){ public void onCancel(DialogInterface dialog) { myTask.cancel(true); //finish(); } });' – Augustus Francis Sep 20 '13 at 07:44
  • Ok, So i put `'pDialog.setOnCancelListener(new DialogInterface.OnCancelListener(){ public void onCancel(DialogInterface dialog) { myTask.cancel(true); //finish(); } });` under my `doInBackGround` method – Inman Douche Sep 20 '13 at 13:52
  • Yeh Define a dialogue on the onPreExecute function and use the above code..As the dialogue gets cancelled so does the task – Augustus Francis Sep 20 '13 at 14:21
  • I will also need an `Exception` for when the asynctask is cancelled right? – Inman Douche Sep 20 '13 at 19:55
  • Sorry for the late response but everything works fine thanks to you!! – Inman Douche Sep 22 '13 at 03:21
0

In this case you will need to write a separate file for your Asynctask class. also make an interface callback.

you do not need to overide the onBackPress button, you just need to set your progressDialog to cancelable(True) and set onCancelListner(). here you can set a flag isCanceld = true;

the whole scenario is defined in this link.

android asynctask sending callbacks to ui

see the answer of Dmitry Zaitsev try this one and let me know if stuck in any where

hope this helps

Community
  • 1
  • 1
Qadir Hussain
  • 8,721
  • 13
  • 89
  • 124
  • ok, I will but cant I also use `abort()` and then catch the Exception when the thing comes down? – Inman Douche Sep 19 '13 at 18:52
  • I don't have idea of abort() method, – Qadir Hussain Sep 20 '13 at 04:39
  • http://stackoverflow.com/questions/18550181/onbackpressed-only-dismissing-progressdialog if you look at the last few comments of the only answer. I was suggested a little while ago that i all need is to call `abort()` and then catch the `Exception` and that will cancel the `AsyncTask` – Inman Douche Sep 20 '13 at 13:48