【问题标题】:EditText.getText().toString() comparison to other string fails [duplicate]EditText.getText().toString() 与其他字符串的比较失败[重复]
【发布时间】:2014-10-22 09:24:37
【问题描述】:

Toast 一直说访问被拒绝,即使我填写了正确的密码。

我需要将用户锁定在自助服务终端模式应用中,并且只有使用正确的 pin,他们才能访问设置和退出选项。

            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();
        }
    });

【问题讨论】:

  • 而不是 'pin == secret' 尝试 pin.equals(secret)

标签: java android string android-edittext tostring


【解决方案1】:

== 测试引用是否相等。

.equals() 测试值相等。

【讨论】:

    【解决方案2】:

    字符串与equals()equalsIgnoreCase() 进行比较,而不是像您使用的那样与双等号== 进行比较。如果它们对大小写敏感,则将 if 语句从 if(pin == secret) 更改为 if(pin.equals(secret)),如果不区分大小写,则将其更改为 if(pin.equalsIgnoreCase(secret))

    【讨论】:

      【解决方案3】:
      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();
                      }
                  });
      

      【讨论】:

        猜你喜欢
        • 2021-02-10
        • 1970-01-01
        • 2015-01-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-13
        • 2013-05-06
        相关资源
        最近更新 更多