1

i have a username and a password string. How can I compare them in Android? This is somewhat what I'm looking for:

if( user== username && pass == password){ then do this  }
else if(user[does not equal to]username && pass==password{ toast (invaild username.)}
else if(user==username && pass[does not equal] password{toast(invaild password)}
else{ toast [invaild login]}

I know that's not correct coding but the two "else if" statements is what I'm looking for. The rest is just to give a better understanding of what I'm trying to do.

The username is what's entered into a Edittext same with the Password so they are both String when i .getText.toString right?

Dakota Miller
  • 493
  • 1
  • 4
  • 22

4 Answers4

2

To compare the text in strings use equals() e.g. pass.equals(password) rather than == which checks if two strings are the same object.

For "does not equal" you can negate the statement e.g. !pass.equals(password).

Jeroen Vannevel
  • 43,651
  • 22
  • 107
  • 170
splrs
  • 2,424
  • 2
  • 19
  • 29
0

You could use pass.equal(password).

apaderno
  • 28,547
  • 16
  • 75
  • 90
0

Use the equals method for comparing strings.

if( user.equals(username) && pass.equals(password))
{
    then do this 
}
else if(!user.equals(username) && pass.equals(password)
{  
 Toast.makeText(this,"invalid username",Toast.LENGTH_SHORT).show();
}
else if(user.equals(username) && !pass.equals(password))
{
Toast.makeText(this,"invalid password",Toast.LENGTH_SHORT).show();
 }
else{ 
Toast.makeText(this,"Invalid login",Toast.LENGTH_SHORT).show(); 
}
Luis Pena
  • 4,132
  • 2
  • 15
  • 23
0

You want to use .equals(..) to compare Strings. Also, to do not logically, you can use !.

//define user, username
//define pass, password
if(user.equals(username) && pass.equals(password)){ 
    //then do this  
}
else if(!user.equals(username) && pass.equals(password)){
    //toast (invaild username.)
    Toast.makeText(getApplicationContext(), "invalid username", Toast.LENGTH_SHORT).show();
}
else if(user.equals(username) && !pass.equals(password)){
    //toast(invaild password)
    Toast.makeText(getApplicationContext(), "invalid password", Toast.LENGTH_SHORT).show();
}
else{ 
    //toast [invaild login]
    Toast.makeText(getApplicationContext(), "invalid login", Toast.LENGTH_SHORT).show();
}

Here are some sources on Toast:

http://www.mkyong.com/android/android-toast-example/

http://developer.android.com/guide/topics/ui/notifiers/toasts.html