How to generate buildConfigField with String type
Asked Answered
M

13

218

In my Android Studio project there are two build configuration with some buildConfigField:

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

    debug {
        buildConfigField "String", SERVER_URL, "http://dev.myserver.com"
        buildConfigField "String", APP_VERSION, "0.0.1"
    }

    release {
        buildConfigField "String", SERVER_URL, "https://myserver.com"
        buildConfigField "String", APP_VERSION, "0.0.1"

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

I am getting and error as follows:

/path/to/generated/BuildConfig.java
    Error:(14, 47) error: ';' expected
    Error:(15, 47) error: ';' expected

the generated BuildConfig.java is as follows:

public final class BuildConfig {
    public static final boolean DEBUG = Boolean.parseBoolean("true");
    public static final String APPLICATION_ID = "com.mycuteoffice.mcoapp";
    public static final String BUILD_TYPE = "debug";
    public static final String FLAVOR = "";
    public static final int VERSION_CODE = 1;
    public static final String VERSION_NAME = "1.0";
    // Fields from build type: debug
    public static final String APP_VERSION = 0.0.1;
    public static final String SERVER_URL = http://dev.mycuteoffice.com;
}

I think the APP_VERSION and SERVER_URL are not getting generated properly as being String type they do not have quotes.

I am not sure why it is being generated in such a way. Please let me know how can I resolve this issues.

Majestic answered 12/6, 2015 at 6:24 Comment(2)
Just add single quotes around the value with double quotes: buildConfigField "String", APP_VERSION, ' "0.0.1" ' (without spaces of course)Omarr
https://mcmap.net/q/128217/-how-to-inject-host-and-schema-in-androidmanifest-xml-for-android-deeplinking can be define on your gradle files :)Abraham
J
355

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.

Jackiejackinoffice answered 12/6, 2015 at 6:28 Comment(8)
The Question intended to use 'SERVER_URL' as a variable. Putting "SERVER_URL" in quotes makes the value a String literal. @madhead's answer is therefore more correct (and prettier).Hen
My bad. I used Simas's answer as a base and just copied it. My point was not about third field (variable name), but about using double quotes for escaping variable value: if the variable itself does not have double quotes, you can simply single outer quotes to get rid of backslashes. I've edited both answers.Trifacial
@VladMatvienko definitely works, I am actually using it the way I describe. def FIELD_NAME = "SERVER_URL" and buildConfigField "boolean", FIELD_NAME, "false" work just fine together. If you're missing the definition of SERVER_URL you'll crash, that's probably what you're doing wrong.Hen
Use buildConfigField "String", "FILE_NAME", "\"{$fileName}\"" for variable names.Psychosocial
@Audi, thanks, but that is exactly what my answer states (for 3 years already)Jackiejackinoffice
If anything i declared like this, its shown when i decompile the apk... How will protect those kind of the secure values?Mainsail
@Kums that does not relate to this question. If you have another question then ask a new question.Jackiejackinoffice
base url is getting displayed even after putting url in build gradle file after decompile apk this is not working.Watchword
T
128

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"'
Trifacial answered 5/5, 2016 at 21:44 Comment(5)
That's still not the way to go, we shouldn't have to escape or use nested quotes it since it's StringMicrocopy
@Microcopy Using nested quotes allows using expressions that can be evaluated. See this answer.Radiophone
Any reason why you put String in double quotes and SERVER_URL in single quotes?Farseeing
@AdamJohns, I guess no. Just to demonstrate that both ' and " could be used.Trifacial
base url is getting displayed even after putting url in build gradle file after decompile apkWatchword
S
41

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)}" }
...
Snide answered 14/10, 2016 at 16:30 Comment(3)
i have a build config field and i want to access that variable in myn def in same gradle .. i am new to gradle plz helpp!!Systemic
Thanks for CONFIG script! In team we slightly improved it to throw exception if var doesn't exists: CONFIG = { k -> if (project.properties.containsKey(k)) "\"${project.properties.get(k)}\"" else throw new RuntimeException("No such variable: " + k) }Mercury
Greate answer, RECOMMEND use itTimoteo
P
19

Use

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

for variable. Reference from here

Psychosocial answered 9/2, 2018 at 10:24 Comment(0)
H
12

Escape your string quotes:

buildConfigField "String", 'SERVER_URL', "\"http://dev.myserver.com\""
buildConfigField "String", 'APP_VERSION', "\"0.0.1\""
Historied answered 12/6, 2015 at 6:32 Comment(0)
T
10

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.

Theseus answered 10/7, 2016 at 10:7 Comment(1)
It's possible if you use string interpolation, e.g: buildConfigField "String", "TEST", "\"${10}\"" This way you can use methods or variables in your build file as well.Wanitawanneeickel
E
5

We should scape our Gradle constant defined in our Gradle properties or somewhere else:

buildConfigField "String", "CONSTANT_NAME", "\"${CONSTANT_VALUE}\""

Where CONSTANT_VALUE is defined in our gradle.properties or somewhere else:

CONSTANT_VALUE=string_goes_here

It applies the same way when getting constants gotten from our environment:

buildConfigField "String", "CONSTANT_NAME", "\"${System.getenv('PATH')}\""

The most voted solution works in case we just need to add a String manually, this solution just goes a step further.

Erl answered 5/9, 2020 at 22:0 Comment(0)
S
4
  1. write code in gradle.properties
YOUR_ACCESS_PARAMS = "YOUR_VALUE"
  1. write code into app level build.gradle
android{
    ...
     buildTypes.each{
        it.buildConfigField 'String', 'ACCESS_PARAMS', YOUR_ACCESS_PARAMS
    }
}
  1. the generated BuildConfig.java is as follows:
public final class BuildConfig {  
    public static final boolean DEBUG = Boolean.parseBoolean("true");   
    public static final String APPLICATION_ID = "xxx.xxxxxxxx.xxx";   
    public static final String BUILD_TYPE = "debug";  
    public static final String FLAVOR = "";  
    public static final int VERSION_CODE = 1;  
    public static final String VERSION_NAME = "1.0.0";  
    // Fields from build type: debug  
    public static final String ACCESS_PARAMS = "YOUR_VALUE";  
}
Sterling answered 5/12, 2022 at 7:2 Comment(0)
T
3

All the answers are groovy.

In .kts format it looks something like this

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

Tamarind answered 27/12, 2023 at 13:8 Comment(1)
Plus one. Thank you. And don't forget to explicit buildConfig = true, inside buildFeatures, inside android, at the same bluid.gradle (module). Then using the value inside a class is the same old way.Esperanto
B
1

in app build.gradle

def buildTimeAndVersion = releaseTime() + "-" + getSvnVersion()    
buildTypes {
debug {
    signingConfig signingConfigs.config
    buildConfigField "String", 'BIULD_TIME', "\"${buildTimeAndVersion}\""
    proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
...
}

static def releaseTime() {
return new Date().format("yyyyMMdd", TimeZone.getDefault())
}

def getSvnVersion() {
def pro = ("svnversion -c " + getBuildDir().parent).execute()
pro.waitFor()
def version = pro.in.text
Pattern p = Pattern.compile("(\\d+\\:)?(\\d+)\\D?")
Matcher m = p.matcher(version)
if (m.find()) {
version = m.group(m.groupCount())
}
try {
return version
} catch (e) {
println e.getMessage()
}
return 0
}

then in BuildConfig

public final class BuildConfig {  
public static final boolean DEBUG = Boolean.parseBoolean("true");   
public static final String APPLICATION_ID = "xxx.xxxxxxxx.xxx";   
public static final String BUILD_TYPE = "debug";  
public static final String FLAVOR = "";  
public static final int VERSION_CODE = 53;  
public static final String VERSION_NAME = "5.4.4";  
// Fields from build type: debug  
public static final String BIULD_TIME = "20181030-2595";  
}
Berrios answered 31/10, 2018 at 3:21 Comment(2)
Code only answers are really discouraged. To help future readers, please explain what you are doing too!Karlsruhe
and next time reference to your previous answer https://mcmap.net/q/128218/-android-buildconfig-field-generating-string-incorrectly instead of just copy pastingGyral
F
1

I need the variable in buildConfigField and manifestPaceholder. To solve this I do

def appAuthScheme= "appauth.myscheme"
buildConfigField 'String', 'APP_AUTH_SCHEME',"\"$appAuthScheme\""

manifestPlaceholders = [lowerApplicationId : applicationId.toLowerCase(),
                        appAuthRedirectScheme : appAuthScheme]

BuildConfig.APP_AUTH_SCHEME is a String !

Frayda answered 25/2, 2021 at 8:39 Comment(0)
B
1

I preferred to highlight that some of those values were strings. At the same time I was not really keen on the escaped quotes for readability reasons.

It might look a little naive, but in the end I settled for this alternative:

buildConfigField "String", "LIB_VERSION_NAME", '"' + "${versionName}" + '"'

and the outcome can look like this:

enter image description here

Benia answered 15/6, 2023 at 9:7 Comment(0)
F
0

Need have def variable

debug {
    ...
    def myVersion = '1.0.0'
    buildConfigField 'String', 'TEST', "\"${myVersion}\""
}
Fivefold answered 7/4, 2023 at 4:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.