Gradle: how to use the external final variable in gradle files

Viewed 617

I have a basic question. In my project, I defined a final varaible in the root build.gradle, like below

final int PUBLISH_TYPE_DEV = 1
allprojects {
    repositories {
    ...
    }
    project.ext {
        versionCode = 63055
        ...
    }
}

Then, I need refer the PUBLISH_TYPE_DEV in the app's build.gradle file. I tried directly "PUBLISH_TYPE_DEV", or project.PUBLISH_TYPE_DEV, or project["PUBLISH_TYPE_DEV"], none of them work for me. It shows "Could not get unknown property 'PUBLISH_TYPE_GREY"" message.

How to use this final variable in the submodule's build.gradle?

4 Answers

In the project build.gradle, you can write this:

buildscript {
    ext {
        PUBLISH_TYPE_DEV = '1'
    }
}

And then, in your module build.gradle, you can refer to it with $PUBLISH_TYPE_DEV

you can make it like this
android{
defaultConfig {
         
         buildConfigField "String", "BaseUrl","\"http:\\example.com\""
                      }
    
        }

and you can use it like this :

BuildConfig.BaseUrl

use this code

Example:

ext {
compileSdkVersion = 29
buildToolsVersion = "29.0.2"
targetSdkVersion = 29
}

calling:

 buildToolsVersion rootProject.ext.buildToolsVersion

Another solution is to have a custom properties file in which you will store your parameters

parameters.properties

# a beautiful comment to explain
PUBLISH_TYPE_DEV=1

Then, in your build.gradle

// Load Configuration
try {
    Properties props = new Properties()
    props.load(new FileInputStream("parameters.properties"))
    props.each { prop -> project.ext.setProperty(prop.key, prop.value) }
} catch (exception) {
    throw new InvalidUserDataException("Parameters not found : $exception.message")
}

if (project.hasProperty("PUBLISH_TYPE_DEV")) {
    // do what you want
} else  {
    throw new InvalidUserDataException('Parameter not found : PUBLISH_TYPE_DEV')
}
Related