2014-08-28 147 views
-3

Toast保持拒絕訪問,即使我填寫正確的引腳。EditText.getText()。toString()與其他字符串的比較失敗

我需要將用戶鎖定到自助服務終端模式應用程序,只有使用正確的引腳,他們才能訪問設置和退出選項。

  public void onClick(View v) { 

      AlertDialog.Builder alert = new AlertDialog.Builder(FullscreenActivity.this); 
      alert.setTitle("PIN:"); 
      //alert.setMessage("Message"); 

      final EditText pinEntry = new EditText(FullscreenActivity.this); 
      alert.setView(pinEntry); 
      alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int whichButton) { 
        String pin = pinEntry.getText().toString().trim(); 
        String secret = "0000"; 
        if (pin == secret){ 
         Toast.makeText(getApplicationContext(),"Access Approved", Toast.LENGTH_SHORT).show(); 
        } 
        else { 
         Toast.makeText(getApplicationContext(),"Access Denied", Toast.LENGTH_SHORT).show(); 
        } 
        Toast.makeText(getApplicationContext(),pin, Toast.LENGTH_SHORT).show(); 
       } 
      }); 

      alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int whichButton) { 
       } 
      }); 
      alert.show(); 
     } 
    }); 
+0

而不是'pin == secret'try pin.equals(secret) – Andromeda 2014-08-28 13:34:42

回答

6

==測試參考平等。

.equals()測試值相等。

3

將字符串與equals()equalsIgnoreCase()進行比較,而不是像您使用的等於==。如果if語句從if(pin == secret)更改爲if(pin.equals(secret))(如果它們是cap-sensitive),或者if(pin.equalsIgnoreCase(secret))(如果case無關緊要)。

0
public void onClick(DialogInterface dialog, int whichButton) { 
        String pin = pinEntry.getText().toString().trim(); 
        String secret = "0000"; 
        if (pin.equalsIgnoreCase(secret)){ 
         Toast.makeText(getApplicationContext(),"Access Approved", Toast.LENGTH_SHORT).show(); 
        } 
        else { 
         Toast.makeText(getApplicationContext(),"Access Denied", Toast.LENGTH_SHORT).show(); 
        } 
        Toast.makeText(getApplicationContext(),pin, Toast.LENGTH_SHORT).show(); 
       } 
      });