强制取消asynctask不起作用

时间:2015-02-24 06:42:09

标签: android android-asynctask

我有一个应用程序,其中包含操作栏中的刷新按钮。当我第二次点击它时,我的应用程序进入调试视图,它说我的asyncClass对象还没有完成!!!

请告诉我如何解决问题。

MyActivity:

public class MyActivity extends ActionBarActivity {

   private getAllDataFromServer asyncClass;    

   @Override
   protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    asyncClass = new getAllDataFromServer();
   }

   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
    // TODO Auto-generated method stub
    if(item.getItemId() == R.id.action_update)
       if(asyncClass.getStatus() == Status.FINISHED || asyncClass.getStatus() == Status.RUNNING)
       {
          asyncClass.cancel(true);
       }
       if(asyncClass.getStatus() == Status.PENDING)
       {
          asyncClass.execute();
       }
    }
    return super.onOptionsItemSelected(item);
}

getAllDataFromServer:

private class getAllDataFromServer extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        pDialog = new ProgressDialog(SendCommentsHistoryActivity.this);
        pDialog.setMessage("Be patient ...");
        pDialog.setCancelable(false);
        pDialog.show();
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... params) {
        if(isCancelled()) return null;
        jObject = jParser.getJSONFromUrl(TAG_URL, param);
        Log.i("JSONNNNNNNNN", jObject.toString());
        try {
            // get json array

            for (int i = 0; i < jArray.length(); i++) 
            {
                // get jsonObjects and fill database
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        fillListView();
        pDialog.dismiss();
        super.onPostExecute(result);
    }

    @Override
    protected void onCancelled() {
        // TODO Auto-generated method stub
        super.onCancelled();
    }
}

更新 JSONParser类:

public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

public JSONParser() {
}

/**
 * Send POST Data to Server & Retrieve JSON From URL
 */
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
    // defaultHttpClient
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(url);
    httpPost.setEntity(new UrlEncodedFormEntity(params,"UTF-8"));
    HttpResponse httpResponse = httpClient.execute(httpPost);
    HttpEntity httpEntity = httpResponse.getEntity();
    is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
    e.printStackTrace();
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(
            is, "UTF8"), 8);
    StringBuilder sb = new StringBuilder();
    String line = null;
    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());
}
// return JSON Object
return jObj;
}

}

错误截屏: enter image description here

任何建议都将受到赞赏......

1 个答案:

答案 0 :(得分:0)

尝试如下

if(!asyncClass.isCancelled()) {
      asyncClass.cancel(true);
}

并在doInBackground()的for循环中写入

@Override
protected Void doInBackground(Void... params) {
    .......................
        // get json array

        for (int i = 0; i < jArray.length(); i++) 
        {
            // get jsonObjects and fill database

          // Escape early if cancel() is called

           if (isCancelled()) break;
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }
    return null;
}

希望这会对你有所帮助。