0

I have this application that uses an AsyncTask and whenever I decide to close it while it's still running, there's slight lag in the closing. Is there any way to fix it?

Here is my code:

private class GetAPI extends AsyncTask<String, Void, ArrayList<Question>> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Log.i("QA", "Begin GETAPI");
    }

    @Override
    protected ArrayList<Question> doInBackground(String... urls) {
        InputStream inputStream;
        try {

            // create HttpClient
            HttpClient httpclient = new DefaultHttpClient();

            // make GET request to the given URL
            HttpResponse httpResponse = httpclient.execute(new HttpGet(urls[0]));

            // receive response as inputStream
            inputStream = httpResponse.getEntity().getContent();

            questions = new ArrayList<>();

            // convert inputstream to string
            if (inputStream != null) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                String line;
                while ((line = reader.readLine()) != null) {
                    JSONArray ja = new JSONArray(line);

                    for (int i = 0; i < ja.length(); i++) {
                        JSONObject jo = (JSONObject) ja.get(i);
                        Log.i("QA", "Retrieved question " + i);
                        questions.add(new Question(jo.getString("questionText"), jo.getInt
                                ("magnetid"), "", jo.getInt("personid"), jo.getInt("id")));
                        questions.get(i).setId(jo.getInt("id"));
                    }
                }
            } else
                throw new InputMismatchException("Didn't work");
        } catch (JSONException | IOException e) {
            e.printStackTrace();
        }

        return questions;
    }

    // onPostExecute displays the results of the AsyncTask.
    @Override
    protected void onPostExecute(ArrayList<Question> strings) {
        super.onPostExecute(strings);
        Log.i("QA", "End GETAPI");
        QuestionAdapter questionAdapter = new QuestionAdapter(questions);
        recyclerView.setAdapter(questionAdapter);
        refreshContent(false);
    }
} 

I don't quite understand why it causes lag on my phone while running the AsyncTaskand closing this app in the recent applications screen. Is it because I'm not overriding the onCancel() method?

silverAndroid
  • 960
  • 3
  • 11
  • 29

1 Answers1

0

You can (and should) close an AsyncTask using methods provided. You can tie your cancel calls to the specific lifecycle methods of your Activity.

How to stop asynctask thread in android?

Community
  • 1
  • 1
Booger
  • 18,579
  • 7
  • 55
  • 72