0

I'm coming from C#, so typically I try to relate everything that i'm doing.

I cannot figure out why the below statement doesn't work. Basically String val = "admin". Then an I have an if statement, however the if statement is always false. I'm sure it's something simple.

Thanks!

 EditText edt = (EditText) findViewById(R.id.email);
    //String val = edt.getText().toString();
    String val = "admin";

    EditText edt2 = (EditText) findViewById(R.id.password);
    String val2 = edt2.getText().toString();
if(val.toString() == "admin") {
String hero = val;
}

6 Answers6

0

use .equals() instead of ==.

for example:

if (val.equals("admin")) ... 
Anirudh Sharma
  • 7,968
  • 13
  • 40
  • 42
PaulT
  • 4,266
  • 2
  • 13
  • 15
0

You should use

if (val.equals("admin")) {
    String hero = val;
}

instead of using an equal sign. Using an equal sign in java is asking if they're the same object, which will be false even if the strings are the same.

Also, be careful with what you're doing inside of the if statement, because the variable "hero" won't be accessible outside of that block.

kcarscad
  • 26
  • 1
0

In Java you can't compare strings using == You need to change your if statment like this

if(val.equals("admin")){}
JDenais
  • 2,956
  • 2
  • 21
  • 30
0

First of all you have never changed the value of String val to anything so there is no need to try convert it to a string in your if statement.

String val = "admin";
if (val == "admin") {
 //code here
}else{
//code here
}

Hope this helps

Whereslee
  • 123
  • 10
0

In java, == operator check the address of each value, and equals() method check the value.

So If you want to compare the value of each string, you should use the equals() method.

Please search for the concept of 'call by reference' and 'call by value'.

And you already declare val to String, so it didn't need toString().

if(val.equals("admin")) {   
     String hero = val;
}
Petro
  • 3,484
  • 3
  • 32
  • 59
Charles
  • 139
  • 6
0

I'm surprised no one mentioned the difference between .matches() and .equals() depending on your needs, what you could also be looking for is .matches()

if(val.toString().matches("admin")) {
String hero = val;
}

Matches checks the match of a String to a regular expression pattern, not the same string.

For example:

"hello".equals(".*e.*"); // false
"hello".matches(".*e.*"); // true
Petro
  • 3,484
  • 3
  • 32
  • 59