1

我想在 json 请求带有空值时取消 AsyncTask,并显示 Toast 消息。

private class PostTask extends AsyncTask<String, Integer, String>
{
    //Before running code in the separate thread
    @Override
    protected void onPreExecute() 
    {

        progressDialog = new ProgressDialog(login.this);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setMessage("please wait...");
        progressDialog.setCancelable(false);
        progressDialog.setIndeterminate(false);
        progressDialog.setMax(100);
        progressDialog.setProgress(0);
        progressDialog.show();
    }
    //The code to be executed in a background thread.
    @Override
    protected  String doInBackground(String... params) 
    {
        String url=params[0];
        Parser parse = new Parser();
        try{    
            String email = textinput.getText().toString();
            String pass = password.getText().toString();
            JSONObject JsonString = parse.getJSONFromUrl(url,email,pass);

            //String email = JsonString.getString("email");
            Constants.ID = JsonString.getString("id");

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

        catch (NullPointerException e){

             publishProgress(1);
            //Toast.makeText(login.this, "Invalid credentials", Toast.LENGTH_LONG).show();
        }
         return "All Done!";
    }
    //Update the progress
    @Override
    protected void onProgressUpdate(Integer... values) 
    {
        //set the current progress of the progress dialog
    //  progressDialog.setProgress(values[0]);  
        //Toast.makeText(login.this, "Invalid credentials", Toast.LENGTH_LONG).show();
    }
    //after executing the code in the thread
    @Override
      protected void onPostExecute(String result) {

          super.onPostExecute(result);
          startActivity(new Intent("com.example.mysampleapp.DASHBOARDTAB"));
          progressDialog.dismiss();      
     }
}

async如果我在请求中获得 nullJSON并在我调用的同一活动中显示消息,是否有任何取消方法来取消任务AsyncTask

4

2 回答 2

2

如果 JSON 为空,请尝试返回错误代码,例如:

   catch (NullPointerException e){

         publishProgress(1);
        return "Error";
    }

然后在onPostExecute()

@Override
  protected void onPostExecute(String result) {
      super.onPostExecute(result);

      if(result.equals("Error")) {
          //Error
      } else {
          startActivity(new Intent("com.example.mysampleapp.DASHBOARDTAB"));
          progressDialog.dismiss();      
      }
 }
于 2012-12-19T12:14:50.337 回答
1

尝试这个:

postTask = new PostTask();

if (postTask != null)
 {
   postTask.cancel(true);
   postTask = null;
}

谢谢。

于 2012-12-19T12:11:39.297 回答