0

In my android project I use many AsynTask in one activity. I need to stop one AsynTask when I start other.

I'm using myAsynTask.cancel(true); in my android project. But it does stop the AsynTask.

protected String doInBackground(String... args) {

        HashMap<String, String> params = new HashMap<>();
        params.put("id", args[0]);

        Log.d("get value: ", params.toString());

        JSONObject json = jParser.makeHttpRequest(url_comment, "GET", params);

        Log.d("All matches: ", json.toString());

        if(isCancelled()) {
            finish();
        }
        else {

            try {

                int success = json.getInt(TAG_SUCCESS);
                if (success == 1) {

                    JSONmatches = json.getJSONArray(TAG_vedio);

                    for (int i = 0; i < JSONmatches.length(); i++) {
                        JSONObject c = JSONmatches.getJSONObject(i);

                        String title = c.getString(TAG_title);
                        String url = c.getString(TAG_url);

                        HashMap<String, String> map = new HashMap<String, String>();

                        map.put(TAG_title, title);
                        map.put(TAG_url, url);

                        arrayList22.add(map);
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
1
  • In this case, you should use a library for webservice requests. For example retrofit is the best choice for this job. the link of it : square.github.io/retrofit. It arranges and supports multi requests. Commented Apr 7, 2016 at 11:30

2 Answers 2

1

You actively have to check for isCancelled while executing your loop in doInBackground.

You should break the loop if isCanceled is true.

Sign up to request clarification or add additional context in comments.

Comments

1

From the official Android documentation:

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.)

3 Comments

it is invoke isCancelled() first but it also invoke onPostExecute(Object) after isCancelled() runs.
check the the isCancelled() value and if it is false then continue your work in postExecute()
if (isCancelled()) { this.cancel(true); } else{ listView.setVisibility(View.GONE); }

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.