Home > Enterprise >  SonarLint: Suppress specific line warning in Android Studio
SonarLint: Suppress specific line warning in Android Studio

Time:07-24

There is a special case in our code where we need to call setText with getText of the same TextView. SonarLint warn this with kotlin:S1656, to suppress it we use @SuppressWarnings annotation but it does not work. It started showing an error to the IDE and the warning from SonarLint still there. //NOSONAR is not working as well

enter image description here

enter image description here

No action is available as well for suppressing it. enter image description here

CodePudding user response:

Can you put the SuppressWarnings annotation before your method?

// Sonarlint plugin version 6.8.0.50884

@SuppressWarnings("kotlin:S1656")
fun yourMethod() {
    // ...
  withContext(coroutineDispatcherMain) {
        // Set the text again to fix images overlapping text
        htmlTextView.text = htmlTextView.text
  }

}

I also wonder that if htmlTextView.invalidate() would work for you.

UPDATE:

SuppressWarnings annotation is also available for LOCAL_VARIABLE but I think the problem is more complicated in kotlin code.

If you examine the byte code of these lines below, you can see that some.num = ... is some.setNum(...) in byte code.

Sonar plugin's code analyser may not handle this kind of kotlin specific codes.

class Sonar {

  private val some = Something(0)
  private var member = 0

  @Deprecated("...")
  fun myNumber(): Int = 1

  fun doThat() {
    // local variable working
    @SuppressWarnings("kotlin:S1874") // Code annotated as deprecated should not be used
    val localNum = myNumber()

    // not working
    @SuppressWarnings("kotlin:S1874")
    some.num = myNumber()

    // not working
    @SuppressWarnings("kotlin:S1874")
    member = myNumber()

    // ...
  }

}

CodePudding user response:

I found the docs for the issue to confirm its the right number: https://rules.sonarsource.com/kotlin/RSPEC-1656

Also read the source at https://github.com/SonarSource/sonarlint-intellij but not much help.

It seems like "// NOSONAR" is what you want (I know you said you tried it, but did you have the space? And have it at the end of the line?)

htmlTextView.text = htmlTextView.text // NOSONAR

Just a guess here, but you could also try:

@SuppressWarnings("RSPEC:S1656")

lastly to check suppress is working you can ignore everything:

@SuppressWarnings("all")
htmlTextView.text = htmlTextView.text

Big discussion here: Turning Sonar off for certain code

This article also gives you options to choose from: https://docs.codescan.io/hc/en-us/articles/360012109711-Ignoring-violations

  • Related