Is it possible to declare a variable in Gradle usable in Java ? Basically I would like to declare some vars in the build.gradle and then getting it (obviously) at build time
None of the above answers gave me any guidelines so I had to spend two hours learning about Groovy Methods.
I wanted be able to go against a production, sandbox and local environment. Because I'm lazy, I only wanted to change the URL at one place. Here is what I came up with:
flavorDimensions 'environment'
productFlavors {
production {
def SERVER_HOST = "evil-company.com"
buildConfigField 'String', 'API_HOST', "\"${SERVER_HOST}\""
buildConfigField 'String', 'API_URL', "\"https://${SERVER_HOST}/api/v1/\""
buildConfigField 'String', 'WEB_URL', "\"https://${SERVER_HOST}/\""
dimension 'environment'
}
rickard {
def LOCAL_HOST = "192.168.1.107"
buildConfigField 'String', 'API_HOST', "\"${LOCAL_HOST}\""
buildConfigField 'String', 'API_URL', "\"https://${LOCAL_HOST}/api/v1/\""
buildConfigField 'String', 'WEB_URL', "\"https://${LOCAL_HOST}/\""
applicationIdSuffix ".dev"
}
}
Alternative syntax, because you can only use ${variable}
with double quotes in Groovy Methods.
rickard {
def LOCAL_HOST = "192.168.1.107"
buildConfigField 'String', 'API_HOST', '"' + LOCAL_HOST + '"'
buildConfigField 'String', 'API_URL', '"https://' + LOCAL_HOST + '/api/v1/"'
buildConfigField 'String', 'WEB_URL', '"https://' + LOCAL_HOST + '"'
applicationIdSuffix ".dev"
}
What was hard for me to grasp was that strings needs to be declared as strings surrounded by quotes. Because of that restriction, I couldn't use reference API_HOST
directly, which was what I wanted to do in the first place.