Search code examples
androidgoogle-cloud-platformapi-key

Android Studio is reading the - sign in my API key as an operation


In my app's gradle I defined my API_KEY as followed (changed it for the purpose of asking this question)

buildTypes.each {it.buildConfigField 'String', 'API_KEY', "AIuvSyTp2TG-P81edjKBRSGWoH8slLeurbg2HOc"}

But when I run the app, it's throwing me this error

com/projecttest/cloudvision/MainActivity.java   
error: cannot find symbol variable AIuvSyTp2TG  
error: cannot find symbol variable P81edjKBRSGWoH8slLeurbg2HOc

Apparently it's treating the - sign in my API key as some kind of operation? How do I fix this?


Solution

  • Simply surround the string with (escaped) quotes:

    buildTypes.each {it.buildConfigField 'String', 'API_KEY', "\"AIuvSyTp2TG-P81edjKBRSGWoH8slLeurbg2HOc\""}
    

    Why does this work? I have no idea. The syntax is pretty well documented in the accepted answer to this question, but I have never been able to find the sort of official, detailed docs for buildTypes that Android provides for, say, their Java classes. (And the source code doesn't make for a very easy read, either.)

    If you are reading this, and know where to find the docs, please leave a comment or suggest an edit!

    Here you can find a reference of examples using "buildConfigField", with "String" option.

    Here you can find information about breaking down the "buildConfigField" Parameters.

    Here, is another example configuring an API_ID.