1

How to set variable depending on current buildType, I have tried this

String url = "https://dev.myurl.com"
tasks.whenTaskAdded { task ->
    if (task.name == 'generateReleaseBuildConfig' || task.name == 'generateDebugBuildConfig') {
        if (task.name == 'generateReleaseBuildConfig') {
            url = "https://prod.myurl.com"
        }
    }
}

But no matter if the current buildType is Release or Debug, the tasks generateReleaseBuildConfig and generateDebugBuildConfig are both executed, so I never get the value depending on the current buildType. I specify that this variable is used later in build script and not in Java code.

I have tried several solutions found in SO but none worked for me

Moussa
  • 4,066
  • 7
  • 32
  • 49

2 Answers2

5

This example is from my own application. It's working fine

Put follow code on your app\build.gradle

buildTypes {
        debug {
            ...
            buildConfigField "String", "SERVER_URL", '"http://..."'
        }
        release {
            ...
            buildConfigField "String", "SERVER_URL", '"http://..."'
        }
}

IMPORTANT: sync your gradle

And then put follow call on your class

String URL = BuildConfig.SERVER_URL

Abner Escócio
  • 2,697
  • 2
  • 17
  • 36
0

You can use buildConfigField. It looks like this:

 buildConfigField('String', 'API_URL', "\"URL\"")

Place it in gradle, under different buildType. And to get it use this:

 BuildConfig.API_URL

That will return this value depends of buildType

UPDATE

Are sure you placed it correctly?

 buildTypes {
         debug {
             //...
             buildConfigField('String', 'API_TEST', "\"URL\"")
         }

         release {
             //...
             buildConfigField('String', 'API_TEST', "\"URL\"")
         }
     }
Ikazuchi
  • 433
  • 2
  • 12
  • I get an error : Could not get unknown property 'BuildConfig' for task ':xxx:yyyy' of type org.gradle.api.DefaultTask. – Moussa May 30 '18 at 11:07
  • Please take a look at example, and if you can not find any mistake, please provide your buildTypes code fragment. – Ikazuchi May 30 '18 at 11:16
  • It still doesn't work, I am using it in a task just before generateReleaseBuildConfig or generateDebugBuildConfig., maybe at this moment buildConfig is not already defined – Moussa May 30 '18 at 12:51