Android gradle build: how to set global variables

GradleAndroid Gradle-Pluginbuild.gradle

Gradle Problem Overview


How can I set a global variable that can be accessed from build.gradle and tasks?

Gradle Solutions


Solution 1 - Gradle

To set a global variable

project.ext.set("variableName", value)

To access it from anywhere in the project:

project.variableName

For instance:

project.ext.set("newVersionName", versionString)

and then...

println project.newVersionName

For more information see: http://www.gradle.org/docs/current/dsl/org.gradle.api.plugins.ExtraPropertiesExtension.html

EDIT: As commented by Dmitry, In new versions you can use the following shorthand:

project.ext.variableName = value

Solution 2 - Gradle

The answer from Guy is excellent. I just want to add the practical code.

Example:

Put something like this in the Project build.gradle:

project.ext {
    minSdkVersion = 21
    targetSdkVersion = 23
}

And put something like this in the Module build.gradle to access it:

    defaultConfig {
        minSdkVersion.apiLevel project.minSdkVersion
        targetSdkVersion.apiLevel project.targetSdkVersion
    }

Solution 3 - Gradle

You can also do this. Let's say you want to add appcompat with the version 25.3.1, you can add a variable version_name in your project level build.gradle.

buildscript{
     ext.version_name = '25.3.1'
}

Now you can add this to your application level build gradle and avoid any conflicts.

compile "com.android.support:appcompat-v7:$version_name"
compile "com.android.support:recyclerview-v7:$version_name"
compile "com.android.support:design:$version_name"

Solution 4 - Gradle

Additional, for dynamic global variables you can define global functions in the master build.gradle file:

First, define your function, for example for git branch:

def getGitBranch = { ->
    def stdout = new ByteArrayOutputStream()
    exec {
        commandLine 'git', 'rev-parse', '--abbrev-ref', 'HEAD'
        standardOutput = stdout
    }
    return stdout.toString().trim()
}

In allProjects section set the variable:

allprojects {
    repositories {
        google()
        jcenter()
    }
    project.ext {
        gitBranch="\"${getGitBranch()}\""
    }
}

In your build.gradle files of your sub projects or android modules, get this variable like this:

android {
    compileSdkVersion project.mCompileSdkVersion.toInteger()
    defaultConfig {
        minSdkVersion project.mMinSdkVersion.toInteger()
        ...
        buildConfigField "String", "GitBranch", project.gitBranch
    }
    ...
}

Finally, you can use it in your code like this:

public static String getGitBranch() {
    return BuildConfig.GitBranch;
}

Solution 5 - Gradle

You cant create a Gradle file in the project's root directory and put all variables there, like this:

lib-versions.gradle

   ext {
        kt_core = '1.6.0'
        app_compat = '1.3.1'
        material = '1.4.0'
        constraintlayout = '2.1.1'
        nav_version = '2.3.5'
        junit = '4.13.2'
        junit_ext = '1.1.3'
        escpresso = '3.4.0'
    }

Then in the project build.gradle file on the bottom you should apply the Gradle file like this:

buildscript {
    ...
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

apply from: 'lib-versions.gradle' //apply it like this

Then you are able to use the variables in any module-level build Gradle file (app/build.gradle) like this:

    implementation "androidx.core:core-ktx:$rootProject.ext.kt_core"
    implementation "androidx.appcompat:appcompat:$rootProject.ext.app_compat"
    implementation "com.google.android.material:material:$rootProject.ext.material"
    implementation "androidx.constraintlayout:constraintlayout:$rootProject.ext.constraintlayout"
    ...

Solution 6 - Gradle

This is for Kotlin DSL (build.gradle.kts).

Root (top-level) build file:

val myVariable by extra("watermelon")
// Alternative notations:
// extra.set("myVariable", "watermelon")
// extra["myVariable"] = "watermelon"

Extra properties on a project object are visible from its subprojects. Note that extra. is equivalent to project.extra.; in other words the project object is implicit.

A sub-project build file:

val myVariable: String by rootProject.extra
// Alternative notations:
// val myVariable: String by rootProject
// val myVariable: String = rootProject.extra["myVariable"] as String
// val myVariable: String = rootProject.extra.get("myVariable") as String

Note that when using Kotlin delegation (by keyword) the name of the variables should be the same in both build files.

See Gradle Docs: Extra properties for more information.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGuyView Question on Stackoverflow
Solution 1 - GradleGuyView Answer on Stackoverflow
Solution 2 - GradlenafsakaView Answer on Stackoverflow
Solution 3 - Gradlemakkor jamalView Answer on Stackoverflow
Solution 4 - GradleHpsaturnView Answer on Stackoverflow
Solution 5 - GradleMeLeanView Answer on Stackoverflow
Solution 6 - GradleMahozadView Answer on Stackoverflow