-2

Scenario: when the focus is lost from an EditText, I'm checking if it contains null (in the first if block).
If so, then I'll show a Toast.
In the else-if block I'm checking if the EditText doesn't contain letters.
Then I'll show a toast, but when I run the application, the Toast is shown even on a correct input.
I.e.: If I enter any letter the Toast should not be shown, it should be shown only when a null or digit/special symbol is entered.

Here is the code

et1.setOnFocusChangeListener(new View.OnFocusChangeListener() {

        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            // TODO Auto-generated method stub
            if(!hasFocus)
            {
                a = et1.getText().toString();
                if (a.equals(""))
                {
                    Toast.makeText(getApplicationContext(), "Your entry is incorrect!!", Toast.LENGTH_LONG).show();
                }
                else if (!a.contains("[a-z]")||!a.contains("[A-Z]")) {
                    Toast.makeText(getApplicationContext(), "Your entry is incorrect!!", Toast.LENGTH_LONG).show();

                }
                else
                {
                }

Please help

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • 1
    possible duplicate of [How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – njzk2 Jul 25 '15 at 18:41
  • 1
    i don't understand, didn't you read the documentation for `contains`, first? – njzk2 Jul 25 '15 at 18:43

3 Answers3

1

It's not working because:

if (a == "")

won't work in Java

Use

if (a.equals(""))

instead


Also, String.contains doesn't use regular expressions, but CharacterSequences.
So, unless your string doesn't contain the exact character sequences "[a-z]" or "[A-Z]" (and only one of these 2 strings), you'll never get a match.

See: http://developer.android.com/reference/java/lang/String.html#contains(java.lang.CharSequence)

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
1

The '==' operator only compares references. To compare string values you must use the equals() method.

Instead of

if (a == "")

use

if (a.equals(""))

See: What is the difference between == vs equals() in Java?

Community
  • 1
  • 1
Zarwan
  • 5,537
  • 4
  • 30
  • 48
0

The problem is:

if (a == "")

Strings can't be compared like this. Instead, check for size equal to 0, or against a specific string with the equals() method.

Larry Schiefer
  • 15,687
  • 2
  • 27
  • 33