2013-05-31 49 views
0

對於android中的登錄頁面,我使用php webservice連接到服務器數據庫。我將來自php服務的響應存儲在一個字符串中。答案應該是成功或失敗。但有時候它既不會成功也不會失敗。所以當時它顯示空指針異常。我嘗試如下,但它是表示行空指針異常如何檢查一個字符串是否在android中返回null值?

如果(!response.equals(空)& & response.equals( 「SUCCESS」))

時響應是空的。我該如何解決這個問題。在這方面請幫助我。

if (!response.equals(null) && response.equals("SUCCESS")) { 
     Intent howis = new Intent(Login.this, Homepage.class); 
     startActivity(in); 
} 
else if (response.equals("FAILED")) { 
     new AlertDialog.Builder(Login1.this) 
       .setMessage(
         "Sorry!! Incorrect Username or Password") 
       .setCancelable(false).setPositiveButton("OK", null) 
       .show(); 
     password.setText(""); 
     username.requestFocus(); 
} else if (response.equals(null)) { 
     new AlertDialog.Builder(Login1.this) 
      .setMessage("Invalid email or password") 
      .setCancelable(false).setPositiveButton("OK", null) 
      .show(); 
     password.setText(""); 
     username.requestFocus(); 
} else { 
     new AlertDialog.Builder(Login1.this) 
      .setMessage("Please Try Again..") 
      .setCancelable(false).setPositiveButton("OK", null) 
      .show(); 
     password.setText(""); 
     username.requestFocus(); 
} 
+0

(response == null || response ==「」) –

+0

將其更改爲if(response!= null)&& response.equals(「SUCCESS」)) –

回答

2

如果你正在檢查一個(與它無關)字符串,則條件應該是:

if (response == null) { 

} else if (response != null) { 

} 

如果你檢查空的String(該字符串的值爲null),則條件應爲:

if (response.equals("null")) { 

} else { 

} 
0

您還可以使用

if(TextUtils.isEmpty(response)) 
{ 
// response is either null or empty 
} 

從文檔:

public static boolean isEmpty (CharSequence str) 
Returns true if the string is null or 0-length. 
0

您可以簡單地使用..

if (!response.equals("") && response.equals("SUCCESS")) 
{ 
... 
} 
1

不能使用像equals()字符串的方法時,它是null 。您應該首先檢查nullresponse == null)。 我會建議做

if (response == null) { 
    //null 
} else if (response.equals("SUCCESS")) { 
    //success 
} else if (response.equals("FAILED")) { 
    //failed 
} else { 
    //neither of those 
} 

if (!response == null && response.equals("SUCCESS")) { 
    //success 
} else if (!response == null && response.equals("FAILED")) { 
    //failed 
} else if (response == null) { 
    //null 
} else { 
    //neither of those 
} 

第一種方式是短,更簡潔,第二個有順序爲你的代碼,有什麼可以爲理解代碼更好。

0

另一種可能的解決方法(對我的作品)是爲了避免由佈局XML中設置的默認值的空指針異常:

的android:文本=「SomeText」則會

也就是說,如果你的卡:-)

相關問題