0

So, this is my Android MainActivity, but specifically this code:

public void checkUser(View view) {
    // Next Activity to move on to
    Intent intentSuccess = new Intent(this, Home.class);
    Intent intentFail = new Intent(this, LoginFailActivity.class);

    EditText usernameText = (EditText) findViewById(R.id.user_field);
    String username = usernameText.getText().toString();

    EditText passwordText = (EditText) findViewById(R.id.pword_field);
    String password = passwordText.getText().toString();

    if (username == "admin" && password == "password") {
        startActivity(intentSuccess);
    } else {
        startActivity(intentFail);
    }
}

Even when I type in "admin" and "password" it goes to intentFail every time. I have checked with a test activity and it properly passes the strings to it without issue.

Please help me and thank you in advance!!

tcatchy
  • 849
  • 1
  • 7
  • 17
  • 3
    Use String equals method to compare string instead of ==. Read this: http://stackoverflow.com/questions/767372/java-string-equals-versus – Juned Ahsan Nov 05 '13 at 03:11

2 Answers2

1

I would say the problem is here...

if (username == "admin" && password == "password")

Should be

if (username.equals("admin") && password.equals("password"))

Java treats strings as Objects not char arrays.

Per comment... Link about this

Community
  • 1
  • 1
Jackie
  • 21,969
  • 32
  • 147
  • 289
  • 1
    Just to clarify, using `==` tests if the two `String`s are references to the same object on the heap, whereas `equals()` tests for equality of each character in the `String`s. – Matt Logan Nov 05 '13 at 03:18
  • What he said I was debating if my char array comment would hurt the explanation. – Jackie Nov 05 '13 at 03:20
1
if (username == "admin" && password == "password") {
        startActivity(intentSuccess);
    } else {
        startActivity(intentFail);
    }

should be

if (username.equals("admin") && password.equals("password") {
        startActivity(intentSuccess);
    } else {
        startActivity(intentFail);
    }