Gradle buildConfigField with integer variable

salcosand picture salcosand · Jul 22, 2016 · Viewed 21.8k times · Source

I would like to define a build config filed where I can use a variable defined in the gradle script it self:

def someVar = 512
android {
...
    buildConfigField 'int', 'SOME_INT_FIELD',  someVar
}

But this produces following error:

Error:(25, 0) Gradle DSL method not found: 'buildConfigField()'

Possible causes:

  • The project 'PROJECT' may be using a version of Gradle that does not contain the method.
  • The build file may be missing a Gradle plugin.

  • I could use quotes like:

    def someVar = 0
    android {
    ...
        buildConfigField 'int', 'SOME_INT_FIELD',  '"' + someVar + '"'
    }
    

    But this comes to a compiler error in BuildConfig

    // Fields from default config.
    public static final int SOME_INT_FILED = "512";
    

    So for now I stay with:

    def someVar = 0
    android {
    ...
        buildConfigField 'String', 'SOME_INT_FIELD',  '"' + someVar + '"'
    }
    

    and use it like:

    final int value = Integer.valueOf(BuildConfig.SOME_INT_FIELD);
    

    Does anybody has better solution or do I use buildConfigField wrong?

    (I also tried using parentheses in combination with any of possibility above.)

    Answer

    Beyka picture Beyka · Jul 28, 2016

    I found a solution, so maybe this answer will help somebody in future.

    def String globalVersionCode
    
    defaultConfig {
        applicationId "com.test.gradle.build"
        minSdkVersion 15
        targetSdkVersion 22
        versionCode 1
        versionName "0.1"
    
        globalVersionCode = versionCode
    }
    
    buildTypes {
        release {
             buildConfigField ("int", "DatabaseVersion", globalVersionCode)
        }
    }
    

    And now in java I can get DatabaseVersion variable:

    public static final int DB_VERSION = BuildConfig.DatabaseVersion;