2016-03-07 150 views
0

我遇到了AsyncTaskdoInBackground方法的問題,我不知道如何阻止此方法運行。在Android中停止AsyncTask doInBackground方法

我正在處理一個應用程序,該應用程序具有一個登錄屏幕,用於檢索有關登錄用戶的信息。問題是,當我輸入了錯誤的密碼或用戶名,然後當我重新輸入正確的數據,我的應用程序崩潰,我得到

「java.lang.IllegalStateException:無法執行任務:任務有 已經已執行「

如何阻止此線程運行?下面是代碼:

LoginActivity.java

public class LoginActivity extends Activity implements LoginParser.GetLoginListener{ 


    public LoginParser parser1; 
    public EditText ETUsername; 
    public EditText ETPassword; 
    //private LoginParser lb; 


    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_login); 


     parser1 = new LoginParser(); 

     ETUsername = (EditText)findViewById(R.id.ET1); 
     ETPassword = (EditText)findViewById(R.id.ET2); 

     final Button button = (Button) findViewById(R.id.loginBut); 

     button.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 

       String UserName = ETUsername.getText().toString(); 
       String Password = ETPassword.getText().toString(); 
       Log.e("LoginAct .. userName: ", UserName); 
       Log.e("LoginAct .. Password: ", Password); 

       if (UserName.isEmpty() || Password.isEmpty()) { 
        new AlertDialog.Builder(LoginActivity.this).setTitle("Warning") 
          .setMessage("Please Enter your Username and Password") 
          .setPositiveButton("OK", new DialogInterface.OnClickListener() { 
           @Override 
           public void onClick(DialogInterface dialog, int which) { 
           } 
          }).show(); 
       } 

       else{ 

        parser1.getLoginInfo(UserName, Password); 
        parser1.setListener(LoginActivity.this); 
       } 
      } // end of button on click 
     }); 
} 

    @Override 
    public void didReceivedUserInfo(String displayName) { 

     if(displayName != null) { 

         new AlertDialog.Builder(LoginActivity.this).setTitle("Welcome").setMessage("Welcome " + displayName) 
           .setPositiveButton("OK", new DialogInterface.OnClickListener() { 
            @Override 
            public void onClick(DialogInterface dialog, int which) { 
             Intent in = new Intent (LoginActivity.this, MainActivity.class); 
             startActivity(in); 
            } 
           }).show(); 
        } 

       else { 

        new AlertDialog.Builder(LoginActivity.this).setTitle("Warning") 
          .setMessage("Error in login ID or Password, Please try again later") 
          .setPositiveButton("OK", new DialogInterface.OnClickListener() { 
           @Override 
           public void onClick(DialogInterface dialog, int which) { 

           } 
          }).show(); 
       } 
    } 
} 

LoginParser.java

public class LoginParser extends AsyncTask <Void,Void,String> { 

    private String requestURL; 

    public String UserName ; 
    public String Password ; 



    public interface GetLoginListener 
    { 
     public void didReceivedUserInfo (String displayName); 
    } 

    private GetLoginListener listener; 


    public GetLoginListener getListener() { 
     return listener; 
    } 

    public void setListener(GetLoginListener listener) { 
     this.listener = listener; 
    } 


    public void getLoginInfo(String userName , String password) 
    { 
     requestURL = "some link"; 

     this.UserName = userName ; 
     this.Password = password ; 

     execute(); // it will call doInBackground in secondary thread 
    } 




    @Override 
    protected String doInBackground(Void... params) { 

     try { 

      URL url = new URL(requestURL); 

      HttpURLConnection urlConnection1 = (HttpURLConnection) url.openConnection(); 


      String jsonString = "LID="+ UserName +"&PWD="+Password+"&Passcode=****"; 
      Log.e("LoginParser","JSONString: " + jsonString); 


      urlConnection1.setDoOutput(true); 
      urlConnection1.setRequestMethod("POST"); 
      urlConnection1.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
      urlConnection1.setRequestProperty("charset","utf-8"); 


      PrintWriter out = new PrintWriter(urlConnection1.getOutputStream()); 
      // out.print(this.requestMessage); 
      out.print(jsonString); 
      out.close(); 

      int statusCode = urlConnection1.getResponseCode(); 
      Log.d("statusCode", String.valueOf(statusCode)); 
      StringBuilder response = new StringBuilder(); 

      byte[] data = null; 

      if (statusCode == HttpURLConnection.HTTP_OK) 
      { 
       BufferedReader r = new BufferedReader(new InputStreamReader(urlConnection1.getInputStream())); 

       String line; 

       while ((line = r.readLine()) != null) { 
        response.append(line); 
       } 

       data = response.toString().getBytes(); 
      } 

      else { 

       data = null;// failed to fetch data 
      } 

      String responseString = new String(data); 
      Log.e("doInBackground", "responseString" + responseString); 

      JSONObject jsonObject2 = new JSONObject(responseString); 
      String Status = jsonObject2.getString("Status"); 
      Log.e("Status", Status); 

      if (Status.equals("s")) { 


       Log.i("Status:", "Successful"); 

       String displayName = jsonObject2.getString("DisplayName"); 


       return displayName; 
      } 

      else { 

       return null; 

      } 

     } catch (ProtocolException e) { 
      e.printStackTrace(); 
     } catch (MalformedURLException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 

     return null; 
    } 

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

     Log.e("onPost: ","onPost"); 
     listener.didReceivedUserInfo(displayName); 
    } 
} 

謝謝您的幫助。

回答

2

「無法重新執行任務」錯誤可以通過創建一個新的AsyncTask實例來解決。您不能在同一個實例上調用兩次執行,但可以根據需要創建多個實例。

停止執行不會幫助那個錯誤。問題不在於它當前正在運行,問題是您需要創建一個新實例並運行它。

+0

它的工作原理。非常感謝。 – Luji

0

您可以在doInBackground方法中使用isCancel的連續檢查取消異步任務。

protected Object doInBackground(Object... x) { 
    while (/* condition */) { 
     // work... 
     if (isCancelled()) break; 
    } 
    return null; 
} 

希望這會對你有所幫助。

相關問題