This error may happen when there is a mismatch between the versions of the Java running in your environment and the required Java version of your project.
I ofter run with this problem between projects since I maintain multiple project (most of them are legacy) and usually fix the issue by selecting the correct Java version.
If you're running on MacOS, you can solve this issue by changing the java your terminal is using:
You can just run
export JAVA_HOME="/Users/YOUR_USERNAME/Library/Java/JavaVirtualMachines/{JAVA_INSTALATION_FOLDER}/Contents/Home"
just replace JAVA_INSTALATION_FOLDER for your desired Java version and YOUR_USERNAME to your username folder. This works for Sequoia 15 or later
You can also do this on Android Studio by opening Settings > Build, Execution, Deployment > Build Tools > Gradle and changing the Gradle JDK version (you can install multiple java versions using Android Studio)