0

My activity it's a simple login activity where (for tests only) it will return true if the username && password are equal and false if not.

But it always return false.

Not even if I convert toString(); example:

String a=(txtUserName.getText().toString() == txtPassword.getText().toString()) ? "equal" : "Nequal";

Full code:

public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_login);
  txtUserName = (EditText) this.findViewById(R.id.txtUname);
  txtPassword = (EditText) this.findViewById(R.id.txtPwd);
  btnLogin = (Button) this.findViewById(R.id.btnLogin);
  btnLogin.setOnClickListener(new OnClickListener() {
    @Override


      public void onClick(View v) {
      Toast.makeText(LoginActivity.this,txtUserName.getText(),Toast.LENGTH_LONG).show();
      Toast.makeText(LoginActivity.this,"Just for separate", Toast.LENGTH_LONG).show();
      Toast.makeText(LoginActivity.this,txtPassword.getText(), Toast.LENGTH_LONG).show();

      String a=(txtUserName.getText() == txtPassword.getText()) ? "equal" : "Nequal";

      Toast.makeText(LoginActivity.this, a, Toast.LENGTH_LONG).show();

    }

  });
}  
Peter Elliott
  • 3,273
  • 16
  • 30
firetrap
  • 1,947
  • 3
  • 24
  • 39

2 Answers2

5

Use

  String a=(txtUserName.getText().toString().equals(txtPassword.getText().toString()))

The way you are doing are not equating string rather they are equating string objects. Always use String.equals() method for string comparison.

Java String.equals versus ==

Community
  • 1
  • 1
Smit
  • 4,685
  • 1
  • 24
  • 28
  • I've tried with the equals: if(txtUserName.getText().equals(txtPassword.getText())){ Toast.makeText(LoginActivity.this, "equal", Toast.LENGTH_LONG).show(); } else{ Toast.makeText(LoginActivity.this, "Nequal", Toast.LENGTH_LONG).show(); } and the return it's the same "Nequal" – firetrap Mar 11 '13 at 18:35
  • `String a=("xyz".equals("xyz"))? "equal" : "Nequal";` I tried this and working fine for me. make sure values your are getting are equal, if they are not then it will return `false`. – Smit Mar 11 '13 at 18:45
  • Thanks its solved with the equals and toString ;) – firetrap Mar 11 '13 at 19:17
1

To compare string values, use String's equals method; the == operator for object references compares for reference equality and since they are two different objects it will always return false.

txtUserName.getText().equals(txtPassword.getText())
rgettman
  • 176,041
  • 30
  • 275
  • 357
  • Actually, there is some JRE magic for String where boxing may result in == returning true more often than might otherwise be expected. The core answer is correct, though -- the poster should use .equals to compare contents. – Mel Nicholson Mar 11 '13 at 18:31