Gradle buildConfigField with an integer variable

I would like to define the assembly configuration where I can use the variable defined in gradle script it self:

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

But this causes the following error:

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

Possible reasons:

The PROJECT project may use a version of gradle that does not contain a method. The gradle plugin may not be in the build file.

I could use quotes like:

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

But this is due to a compiler error in BuildConfig

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

So now I am staying 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 anyone have a better solution or am I using buildConfigField incorrectly?

(I also tried using parentheses in conjunction with any possible possibility above.)

+9
source share
4 answers

I found a solution, so maybe this answer will help someone in the 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 the DatabaseVersion variable:

 public static final int DB_VERSION = BuildConfig.DatabaseVersion; 
+32
source

The declaration of the int field in build.gradle should not and does not require analysis on the java side. The only mistake in your code is the use of double quotes. The correct path is given below-

 buildConfigField 'int', 'SOME_INT_FIELD', '512' 

Given the above in your build.gradle file, you can use it simply as an int in Java code-

 public static final int SOME_INT_FIELD = BuildConfig.SOME_INT_FIELD; 
+4
source

Try it:

 int val = 10 buildConfigField 'int', 'SOME_INT_FIELD', val.toString() 
+4
source
 def someVar = 100 buildConfigField 'int', 'SOME_INT_FIELD', String.valueOf(someVar) 

I use the above to resolve the issue, hope to help you.

0
source

All Articles