Inman Douche
Inman Douche

Reputation: 139

onBackPressed only dismissing ProgressDialog

I have realized that i have a little issue with my asynctask. I realized that when I press the back button on an android device to dismiss my progress dialog and my asynctask, only my progress dialog is being dismissed and my asynctask still executes. I really do not know why this is happening so I was just hoping if somebody can get me back on the right track and help me with this problem.

    @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();
        }  
    }

        protected String doInBackground(String... args) {

            if (isCancelled()){break;}

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

                    //JSONArray Answers = question.getJSONObject(TAG_ANSWERS).getJSONArray(TAG_ANSWER);


                    //JSONObject Answer = Answers.getJSONObject(0);

                    //String Content = Answer.getString(TAG_ANSWERS_CONTENT);

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

                               map.put(TAG_QUESTION_SUBJECT, Subject);
                               map.put(TAG_QUESTION_CONTENT, Content);
                               map.put(TAG_QUESTION_CHOSENANSWER, ChosenAnswer);

                               questionList.add(map);

                    }


                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

                return TAG_QUESTION ;           

        }

JSONParsser:

public class JSONParsser {

    InputStream is = null;
    JSONObject jObj = null;
    String json = "";
    public EditText et;

    public JSONParsser () {
    }

    public JSONObject readJSONFeed(String URL) {

        try{
        HttpClient client = new DefaultHttpClient();
        HttpPost request = new HttpPost(URL);
        //request.setURI(website);
        try {
            HttpResponse response = client.execute(request);
        HttpEntity httpEntity = response.getEntity();
        is = httpEntity.getContent();

        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
           Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        Log.d("JSON String",json);

        return jObj;

        }finally{}

    }{
    }

}

Upvotes: 2

Views: 1144

Answers (1)

dst
dst

Reputation: 3337

You have to implement cancelling features within the AsyncTasks doInBackground method, if you wish to cancel its execution.

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?

From the Android docs:

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

Upvotes: 3

Related Questions