"ERROR: JAVA_HOME is set to an invalid directory" - but I set it to the Android Studio's Gradle JDK as instructed

Hi, I’m trying to set up capacitor for the first time and have run into an error when following the documentation. I’m at the stage where I run npx cap run android in my project. On doing so I initially got this error:

[error] The operation couldn’t be completed. Unable to locate a Java Runtime.

I googled this error and found this post with a solution. Since I’m using Android Studio’s emulator, it directed me to “find the SDK path in Android Studio (Android Studio > Preferences… > Build, Execution, Deployment > Build Tools > Gradle > Gradle JDK)”. I did this and set the following as JAVA_HOME:

export JAVA_HOME="/Applications/Android\ Studio.app/Contents/jre/Contents/Home"

This is definitely the right path for Android Studio’s JDK. However now when I run npx cap run android I get:

ERROR: JAVA_HOME is set to an invalid directory: /Applications/Android\ Studio.app/Contents/jre/Contents/Home"

How do I fix this? Thanks!

I think if you remove the \ like this:

export JAVA_HOME="/Applications/Android Studio.app/Contents/jre/Contents/Home"

or keep the \, and then remove the double quotes instead:

export JAVA_HOME=/Applications/Android\ Studio.app/Contents/jre/Contents/Home

Both of these 2 methods should solve the issue.

The reason why export JAVA_HOME="/Applications/Android\ Studio.app/Contents/jre/Contents/Home" won’t work is because Enclosing characters in double quotes (") preserves the literal value of all characters within the quotes, with the exception of $, `, \.

This means, when enclosing a string in double quotes ("), white-space characters do not need to be escaped. The only characters that require escaping within double quotes are ", $, `, and \, which should be replaced with \", \$, \`, and \\, respectively.

Bash Reference:

Zsh Reference:

That worked, thanks so much!