Im trying to compare the values of two edittext boxes. What i would like is to just compare passw1 = passw2. As my code is now comparing two strings i have entered as i could not get to compare them.
final EditText passw1= (EditText) findViewById(R.id.passw1);
final EditText passw2= (EditText) findViewById(R.id.passw2);
Button buttoks = (Button) findViewById(R.id.Ok);
buttoks.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if (passw1.toString().equalsIgnoreCase("1234") && passw2.toString().equalsIgnoreCase("1234")){
Toast.makeText(getApplication(),"Username and password match", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(getApplication(),"Username and password doesn't match", Toast.LENGTH_SHORT).show();
}
} });
To compare these strings in Java, we need to use the equals() method of the string. You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not.
Using String. equals() :In Java, string equals() method compares the two given strings based on the data/content of the string. If all the contents of both the strings are same then it returns true. If any character does not match, then it returns false.
equals() checks if two objects are the same or not and returns a boolean. compareTo() (from interface Comparable) returns an integer. It checks which of the two objects is "less than", "equal to" or "greater than" the other. Not all objects can be logically ordered, so a compareTo() method doesn't always make sense.
Java String compareTo() Method The compareTo() method compares two strings lexicographically. The comparison is based on the Unicode value of each character in the strings. The method returns 0 if the string is equal to the other string.
In onclik function replace first line with this line u will definitely get right result.
if (passw1.getText().toString().equalsIgnoreCase("1234") && passw2.getText().toString().equalsIgnoreCase("1234")){
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With