Home > Blockchain >  Android button refuses to change activity
Android button refuses to change activity

Time:08-15

Iam creating a simple login screen to change the activity as a practice even all of my code is right but when I click the button nothing happens neither the IF is true nor false

public class MainActivity extends AppCompatActivity {

private EditText name;
private EditText password;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    name = findViewById(R.id.username);
    password = findViewById(R.id.password);
    Button login = findViewById(R.id.login);
    
    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Login(name.getText().toString(),password.getText().toString());
        }
    });

}

private void Login(String username,String password) {

    if((username == ("Santos")) && (password == "1234")) {
        Intent intent = new Intent(MainActivity.this, MainActivity2.class);
        startActivity(intent);
    }
}}

note: the button itself works without the IF function

CodePudding user response:

Your login method compares strings by their object references. You have to compare them by their values.

When you call getText(), you will have a string object created with another object reference.

String name = "Santos"; // is object #7890
// Let's say username from getText() is object #4758

// will be always false
if (username == "Santos") {}

Check out the code below.

public class StringCompare {

   public void login(String username, String password) {
      if (username.equals("Santos") && password.equals("1234")) {
         System.out.println("Login successful");
      } else {
         System.out.println("Login failed");
      }

      if (username == "Santos" && password == "1234") {
         System.out.println("Login successful with reference check");
      } else {
         System.out.println("Login failed at reference check");
      }

      System.out.println();
   }

   public void testLogin(){
      String password = "1234";
      String username = "Santos";

      // creating another string object
      String anotherString = new String("Santos"); 

      // also creating another string object
      String something = new StringBuilder("Santos").toString();

      login(username, password);
      login(anotherString, password);
      login(something, password);
   }
}
  • Related