2015-10-01 175 views
1

在LoginActivity.java類中,當用戶單擊註冊按鈕時,代碼將登錄會話設置爲true,然後將活動從LoginActivity切換到MainActivity。這是登錄代碼片段。Android:拋出IllegalStateException異常

  case(R.id.login): 
       String email = etEmail.getText().toString(); 
       String password = etPassword.getText().toString(); 

       if(email.trim().length() > 0 && password.trim().length() > 0) { 
        loginManager.checkLogin(email, password); 
        pDialog.setMessage("Logging in.."); 
        showDialog(); 
        session.setLogin(true); 

        if(loginManager.isLoginSuccessful()) { 
         hideDialog(); 
         Toast.makeText(this, getResources().getString(R.string.welcome_msg), Toast.LENGTH_LONG).show(); 
         Intent intent = new Intent(this, MainActivity.class); 
         startActivity(intent); 
         overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left); 
         finish(); 
        } else { 
         Toast.makeText(this, loginManager.getErrorMessage(), Toast.LENGTH_LONG).show(); 
        } 

       } else if(email.trim().length() < 1) { 
        Toast.makeText(this, "Please enter the email", Toast.LENGTH_SHORT).show(); 
       } else { 
        Toast.makeText(this, "Please enter the password", Toast.LENGTH_SHORT).show(); 
       } 
       break; 

這裏是LoginManager.java文件,它處理登錄過程。我使用OkHttp作爲HTTP庫。

public class LoginManager { 
    private final String TAG_LOGIN = LoginManager.class.getSimpleName(); 
    private OkHttpClient client = new OkHttpClient(); 
    private final String loginURL = URL.getInstance().getUrlLogin(); 
    private Request request = new Request.Builder().url(loginURL).build(); 

    private static JSONObject jsonObject; 
    private boolean error; 

    public void checkLogin(final String email, final String password) { 

     client.newCall(request).enqueue(new Callback() { 

      // onFailure is called when the request could not be executed due to cancellation, a connectivity problem or timeout. 
      @Override 
      public void onFailure(Request request, IOException e) { 

      } 

      // onResponse is called when the HTTP response was successfully returned by the remote server. 
      // using POST request for login 
      @Override 
      public void onResponse(Response response) throws IOException { 
       Log.d(TAG_LOGIN, "Login response: " + response.body().string()); 
       RequestBody body = new FormEncodingBuilder() 
         .add("tag", "login") 
         .add("email", email) 
         .add("password", password) 
         .build(); 
       Request request = new Request.Builder().url(loginURL).post(body).build(); 
       client.newCall(request).execute(); 

       try { 
        jsonObject = new JSONObject(response.body().string()); 
        error = jsonObject.getBoolean("error"); 
       } catch(JSONException e) { 
        e.printStackTrace(); 
       } 
      } 
     }); 
    } 

    public boolean isLoginSuccessful() { 
     if(error) { 
      return false; 
     } 
     return true; 
    } 

    public String getErrorMessage() { 
     String errorMessage = null; 
     try { 
      jsonObject.getString("error_msg"); 
     } catch(JSONException e) { 
      e.printStackTrace(); 
     } 

     return errorMessage; 
    } 
} 

當我運行該應用程序時,它顯示歡迎Toast消息並突然退出並顯示以下錯誤日誌。

java.lang.IllegalStateException: closed 
      at com.squareup.okhttp.internal.http.HttpConnection$FixedLengthSource.read(HttpConnection.java:454) 
      at okio.Buffer.writeAll(Buffer.java:574) 
      at okio.RealBufferedSource.readByteArray(RealBufferedSource.java:87) 
      at com.squareup.okhttp.ResponseBody.bytes(ResponseBody.java:56) 
      at com.squareup.okhttp.ResponseBody.string(ResponseBody.java:82) 
      at com.marshall.thequizshow.application.http.LoginManager$1.onResponse(LoginManager.java:51) 
      at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:150) 
      at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33) 
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
      at java.lang.Thread.run(Thread.java:841) 

因此,我必須在LoginManager.java文件中的onResponse方法下有一個try-catch短語的錯誤。

try { 
        jsonObject = new JSONObject(response.body().string()); 
        error = jsonObject.getBoolean("error"); 
       } catch(JSONException e) { 
        e.printStackTrace(); 
       } 

我想問你,我應該怎麼修復代碼,以便它不再惹人IllegalStateException異常。

預先感謝您。

+0

你如何確定它正在捕獲異常?'IllegalStateException'不會被'JSONException' catch塊捕獲,因爲它們不是在父 - 子關係中。我認爲你得到的堆棧跟蹤是正常的,你可以在JSONException異常中放置一個記錄器,你會發現它沒有被記錄,這意味着它已經不是捕捉..如果你不使用IllegalStateException或RuntimeException或Exception,那麼IllegalStateException將不會被捕獲到任何catch塊。 – hagrawal

回答

7

作爲一般性答案,YES:避免RuntimeException的正確方法是修復代碼:在正常情況下,它們不應該被程序捕獲。

現在,我們來看看你的情況... IllegalStateException的出現是因爲HttpConnection在嘗試使用它時似乎已關閉。難道是因爲你打電話給方法response.body()

+0

每個響應只能調用一次response.body()。string() 。同時要小心,如果你有這個坐在你的「觀看」名單,因爲它也可以算。 https://github.com/square/okhttp/issues/1240 –

-2

在錯誤的時間調用方法時會拋出IllegalState異常。檢查你的過程的性質,然後重構你的代碼以在適當的時間撥打電話

相關問題