1

I have a small code which gives an incorrect lint warning:

int myfunc(@Nullable valStr) {
    int val = -1;
    if (!TextUtils.isEmpty(valStr)) {
        try {
            val = valStr.startsWith("1-"); //<== lint warning here : NullPointerException
        } catch (Exception e) {
        }
    }

    return val;
}

This code gives lint warning that says valStr may be null which is impossible because I have checked valStr with TextUtils.isEmpty(). How I can disable this warning for the if block statement?I don't want to disable it for the whole function with @SuppressLint.

Afshin
  • 8,839
  • 1
  • 18
  • 53
  • Check this out: [How to tell IDEA/Studio that the null check has been done?](https://stackoverflow.com/questions/19302211/how-to-tell-idea-studio-that-the-null-check-has-been-done/53652618#53652618) and [TextUtils.isEmpty checks for null but lint doesn't recognise](https://stackoverflow.com/questions/55635564/textutils-isempty-checks-for-null-but-lint-doesnt-recognise) – Md. Asaduzzaman Jan 21 '20 at 09:09

2 Answers2

2

The simple code comment for disabling the warning is:

//noinspection SimplifiableIfStatement

This on top of the if-statement should switch off the warning only at that place.

In the example, this would be:

int myfunc(@Nullable valStr) {
    int val = -1;

    //noinspection SimplifiableIfStatement
    if (!TextUtils.isEmpty(valStr)) {
        try {
            val = valStr.startsWith("1-"); //<== lint warning here : NullPointerException
        } catch (Exception e) {
        }
    }

    return val;
}
Kalpesh Rupani
  • 991
  • 4
  • 12
  • it seems this comment does not work in android studio. as mentioned here: https://stackoverflow.com/questions/34340056/noinspection-keyword-list-in-android-studio – Afshin Jan 21 '20 at 09:02
  • You should mention the exact warning type, e.g.: `//noinspection LaunchActivityFromNotification` to suppress the warning inspection. – YUSMLE Dec 06 '22 at 14:37
1

Instead of !TextUtils.isEmpty(valStr) do valStr != null. This way lint will know that you have checked the value for null.

Alternatively you could use assert like this: assertNotNull(valStr)

Simon
  • 1,657
  • 11
  • 16
  • 1
    This method is obvious. But when `TextUtil.isEmpty()` is doing both, I prefer to use that function. – Afshin Jan 21 '20 at 08:54
  • You actually don't have to check if it's empty, since startsWith will return -1 if there is no match in the not null string. – Simon Jan 21 '20 at 08:57
  • The code here is just a simple code to show the warning. My real code is more complex which needs to be run when it is not empty or null. – Afshin Jan 21 '20 at 09:02
  • I think you should use assert in this case. Check the updated answer. – Simon Jan 21 '20 at 09:05