Wednesday, April 27, 2022

[FIXED] Why there is 'NullPointerException' warning when I already use !TextUtils.isEmpty()?

Issue

I am using following code:

Editable editable = popupSearchETHP.getText();

if (!TextUtils.isEmpty(editable)) {
      final String fieldVal = editable.toString();
}

and

final String fieldVal = editable.toString();

this statement produces warning:

Method invocation 'toString' may produce 'NullPointerException'

Why???? I am already checking if it is empty or not. But it still produces warning. If you look at source code of TextUtils.isEmpty() then you will find that:

 /**
 * Returns true if the string is null or 0-length.
 * @param str the string to be examined
 * @return true if str is null or zero length
 */
public static boolean isEmpty(@Nullable CharSequence str) {
    return str == null || str.length() == 0;
}

it already checks for null and it also checks its length and then returns result. So why there is warning Method invocation 'toString' may produce 'NullPointerException'?


Solution

I don't know why there is warning when using !TextUtils.isEmpty() but I crafted my custom function which will work similarly and will not produce any warning:

private boolean isNotEmpty(CharSequence str) {
        return (str!=null && str.length() > 0);
    }

//Use this like below
if(isNotEmpty(editable))
{ }

You can also instead use

//noinspection ConstantConditions

if you need to remove the warning only on a specific line.



Answered By - Chaitanya Karmarkar
Answer Checked By - Marie Seifert (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.