Afshin
Afshin

Reputation: 9173

How to disable this incorrect lint warning for a single code block?

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.

Upvotes: 1

Views: 833

Answers (2)

Simon
Simon

Reputation: 1737

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)

Upvotes: 1

Kalpesh Rupani
Kalpesh Rupani

Reputation: 1049

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;
}

Upvotes: 2

Related Questions