Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate buildConfigField with String type

String type build config fields should be declared like this:

buildConfigField "String", "SERVER_URL", "\"http://dev.myserver.com\""

the field name in quotes, the field value in escaped quotes additionally.


Why everybody is so mad about escaping double quotes? Looks ugly! This is Groovy, guys, you can just mix single and double quotes:

buildConfigField "String", 'SERVER_URL', '"http://dev.myserver.com"'
buildConfigField "String", 'APP_VERSION', '"0.0.1"'

If by "resolving the issues" you mean not having to double quote literals, I haven't come across anything as it seems to be working as designed.

I've been experimenting with moving the literals into "gradle.properties" as a workaround, turning potentially multiple ugly lines into one ugly line.

Like so:

buildTypes {
def SERVER_URL = "SERVER_URL"
def APP_VERSION = "APP_VERSION"

def CONFIG = { k -> "\"${project.properties.get(k)}\"" }

debug {
    buildConfigField "String", SERVER_URL, CONFIG("debug.server.url")
    buildConfigField "String", APP_VERSION, CONFIG("version")
}

release {
    buildConfigField "String", SERVER_URL, CONFIG("release.server.url")
    buildConfigField "String", APP_VERSION, CONFIG("version")

    minifyEnabled false
    proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}

gradle.properties

version=0.1.1
...
debug.server.url=http://dev.myserver.com
...
release.server.url=http://myserver.com
...

Further thoughts:


def CONFIG = { b,k -> "\"${project.properties.get(b+'.'+k)}\"" }
def CONFIG_DEBUG = { k -> CONFIG('debug',k) }
def CONFIG_RELEASE = { k -> CONFIG('release',k) }

def CONFIG = { b,k -> "\"${project.properties.get(b+'.'+k)}\"" }
def CONFIG_INT = { b,k -> "${project.properties.get(b+'.'+k)}" }
...

Use

 buildConfigField "String", "FILE_NAME", "\"{$fileName}\"" 

for variable. Reference from here


Escape your string quotes:

buildConfigField "String", 'SERVER_URL', "\"http://dev.myserver.com\""
buildConfigField "String", 'APP_VERSION', "\"0.0.1\""

I was confused as well. But there is a sense - "String" defines the field's type, whereas the field value isn't get quoted automatically in order to allow us to use expressions here:

buildConfigField "String", "TEST", "new Integer(10).toString()"

Otherwise, it wouldn't be possible.