0

In my app I was using EditText. I would like to assign numberOfYearsBirthday=0 when there is no text in the edittext.

I have tried the following code and debugged. I have seen that even if my charSequence="" but it ignore the statement and move to the else statement and thus cause error and crash my app assigning null value as an integer.

xB1.addTextChangedListener(new TextWatcher(){

    @Override
    public void onTextChanged(CharSequence charSequence, int start, int before, int count) {                                        

        if(String.valueOf(charSequence)==null){
            numberOfYearsBirthday=0;
        }else{numberOfYearsBirthday= Integer.valueOf(charSequence.toString());
        }

I have also tried the following code

charSequence.toString()==""

Moreover, the following one too

charSequence ==""

but the program is overlooking my if statement. What's the wrong I am doing here?

Banana
  • 2,435
  • 7
  • 34
  • 60
abc
  • 275
  • 3
  • 11

2 Answers2

3

If charSequence is null, then using String::valueOf will return the text "null" which is different to a null reference and hence your condition won't work. Also doing charSequence.toString()=="" won't work because this is not the proper way to compare Strings in Java.

Try this instead:

// check if charSequence is null or empty ""
if (charSequence == null || charSequence.toString().isEmpty()) {
    numberOfYearsBirthday = 0;
} else {
    numberOfYearsBirthday = Integer.valueOf(charSequence.toString());
}
Juan Carlos Mendoza
  • 5,736
  • 7
  • 25
  • 50
  • I have got it. But one more thing. if (charSequence.toString().isEmpty()) --is working fine. What's the benefit of using "charSequence == null" ? – abc Feb 09 '18 at 19:33
  • if `charSequence` is null and you do `charSequence.toString().isEmpty()` then you would get a [`NullPointerException`](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it). – Juan Carlos Mendoza Feb 09 '18 at 19:35
0

use TextUtils.isEmpty(charSequence).

Your error for the first solution only checks for null which is not the same as an empty String.

The second one does not work because the correct way to check Strings for value equality in Java is stringValue.equals(""). == will check if the two Strings are the same instance of the String, which they aren't.

Hendrik Marx
  • 709
  • 4
  • 9