importing NotNull or Nullable and Android Studio won't compile

When I add @NotNull or @Nullable annotations to a parameter Android Studio automatically helps me with adding /lib/annotations.jar and importing

import org.jetbrains.annotations.NotNull
import org.jetbrains.annotations.Nullable;

But after this, the project won't compile. If I also remove the annotations but keep the import statements the project still won't compile. But if I remove the import statements for NotNull and Nullable the project compiles fine!

Android Studio gives a generic error:

Gradle: 
FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':Bugtester:compileDebug'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

Running gradlew compileDebug from cmd gives a slight hint:

:Bugtester:compileDebug FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':Bugtester:compileDebug'.
> Cannot find System Java Compiler. Ensure that you have installed a JDK (not just a JRE) and configured your JAVA_HOME system variable to point to the according directory.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

So I checked my environment variables and they are set as:

JAVA_HOME=C:\Program Files (x86)\Java\jre7
JDK_HOME=C:\Program Files\Java\jdk1.7.0_21\

Anyone got any idea for this? (I'm new to both java and android programming)


Solution 1:

I guess, the right way is using original JetBrains library from MavenCentral repository in your build.gradle dependencies (latest available version in this example):

dependencies {
    implementation 'com.intellij:annotations:+@jar'
    ...
}

Solution 2:

You can also use android's own @NonNull & @Nullable:

  • Add the following to build.gradle:

    dependencies {
        ...
        // For @Nullable/@NonNull
        compile 'com.android.support:support-annotations:+'
    }
    
  • Go to File / SettingProject SettingsInspections and search for "nullable".

    In Constant conditions & exceptions and @NotNull/@Nullable problems, click Configure annotations and select Android's annotations.

    You may also want to check out Suggest @Nullable annotations… under Constant conditions & exceptions, or possibly tweak other options.