0

我已经使用硬编码密码编写了用于登录身份验证的简单代码。我的问题是即使我输入了正确的密码,我的控制也会进入 elese 循环

edt=(EditText)findViewById(R.id.edt);
btn=(Button)findViewById(R.id.sub);
s1=edt.getText().toString();

btn.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
      Log.d("mynameeeeee",s1);
      if(s1=="123")
      {
        Toast.makeText(getApplicationContext(), "Successful",Toast.LENGTH_LONG).show();
      }
      else
      {
         Log.d("coming in elseeeee","coming in elseeeee");
         Toast.makeText(getApplicationContext(), "not valid",Toast.LENGTH_LONG).show();
      }
    }
 }); 
4

4 回答 4

2

Here's the problem :

You are storing a reference of the edit text content at creation time, when the edit text is empty.

You should retrieve the content of the edit text EVERYTIME you want to compare, which is when the button is clicked in your case :

Do the following :

edt=(EditText)findViewById(R.id.edt);
btn=(Button)findViewById(R.id.sub);

btn.setOnClickListener ( new OnClickListener () {
    @Override
    public void onClick ( View v ) {
            Log.d ( "mynameeeeee" , edt.getText().toString() );
            if ( edt.getText().toString().equals ( "123" ) )
            {
                Toast.makeText(getApplicationContext(), "Successful",Toast.LENGTH_LONG).show();
            }
            else
            {
                Log.d("coming in elseeeee","coming in elseeeee");
                Toast.makeText(getApplicationContext(), "not valid",Toast.LENGTH_LONG).show();
            }

        }
    }); 
于 2012-09-25T10:00:10.420 回答
2

字符串应该像这样比较:

if(s1.equals("123")) {}
于 2012-09-25T09:49:50.333 回答
2

像这样更改您的 if 语句

if(s1.equals("123"))
{
      Toast.makeText(getApplicationContext(), "Successful",Toast.LENGTH_LONG).show();
}
else
{
       Log.d("coming in elseeeee","coming in elseeeee");
       Toast.makeText(getApplicationContext(), "not valid",Toast.LENGTH_LONG).show();
}

比较字符串时总是使用.equals()函数

于 2012-09-25T09:50:16.757 回答
1

==检查两个变量是否都引用同一个对象。在这种情况下,因为它们指的是不同的对象,所以结果==是错误的。

使用 equals() 方法s1.equals("123")检查字符串对象的内容。

于 2012-09-25T09:53:13.983 回答