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?

4
  • if( charSequence == null || charSequence.length() == 0 ){..} Commented Feb 9, 2018 at 19:21
  • Why do I need to use "charSequence == null" ? Commented Feb 9, 2018 at 19:34
  • Because according to you question it can be possible that charSequence will be null too. Commented Feb 9, 2018 at 19:39
  • String.valueOf() doesn't return null. If you want to check charSequence for null, compare it to null, with the == operator. Commented Feb 10, 2018 at 0:38

2 Answers 2

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());
}
Sign up to request clarification or add additional context in comments.

2 Comments

I have got it. But one more thing. if (charSequence.toString().isEmpty()) --is working fine. What's the benefit of using "charSequence == null" ?
if charSequence is null and you do charSequence.toString().isEmpty() then you would get a NullPointerException.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.