Android Studio build failing due to Gradle NullPointerException

I recently experienced problems with Android Studio, where it would no longer clean or rebuild a particular project.

 

The Gradle Console showed this message:

FAILURE: Build failed with an exception.

* What went wrong:
java.lang.NullPointerException (no error message)

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

 

Tried selecting: File menu -> Invalidate Caches / Restart…

Unfortunately this had no effect.

 

Looked for more details by building from a commandline with the suggested options:

gradlew build --stacktrace --debug > build_debug_log.txt 2> build_debug_error.txt

 

(It was neccessary to log standard output and error output separately, because otherwise they would get mixed up)

However the Gradle output still didn’t explain clearly why the build process was failing.

 

Found a suggestion to delete the .gradle folder in the project folder here:

http://stackoverflow.com/questions/39183674/java-lang-nullpointerexception-no-error-message

 

I closed the Android Studio project, moved the .gradle folder outside of the project folder and reopened the Android Studio project.

This solved the problem!

It was now possible to clean and rebuild the project again.

Conclusion

If Android Studio refuses to build due to NullPointerException from Gradle, try removing or moving the .gradle folder from the affected project.