Use variables to manage gradle android dependencies library version numbers

Ivan
2 min readDec 1, 2015

--

In gradle under dependencies. We usually do the following:

dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile "com.android.support:support-v4:23.1.1"
compile "com.android.support:appcompat-v7:23.1.1"
...
}

This is ok if you are using one or two support libraries, or third party libraries. But as the code grows and the requirements in a project increase you might end up with a list of 10 or more libraries, including the support-test libraries and so on.

The problem arises when you get a new update of those libraries. You will have to manually edit each line of code and copy and paste. It will be a waste of time to do that. You have better things to do.

Solution

Use ext variables in your gradle files to put the version number in one place and manage all those version numbers in one single place in gradle. It will look something like this:

There are two ways of doing this.

Put your version numbers in a variable in your ROOT build.gradle file

ext{
//dependencies
junitVersion = '4.12'
mockitoVersion = '1.10.19'
powerMockito = '1.6.2'
hamcrestVersion = '1.3'
runnerVersion = '0.4.1'
rulesVersion = '0.4.1'
espressoVersion = '2.2.1'
supportLibraryVersion = '23.1.1'
guavaVersion = '18.0'
}

Now back in your app module build.gradle file you can use those variables like this.

dependencies {
...
compile "com.android.support:appcompat-v7:$rootProject.ext.supportLibraryVersion"
compile "com.android.support:support-v4:$rootProject.ext.supportLibraryVersion"
...
}

You can also define ext in your app module build.gradle file directly if you think it is a better approach like this:

ext.supportLibraryVersion = '23.1.1'
dependencies {
...
compile "com.android.support:appcompat-v7:$supportLibraryVersion"
...
}

I hope that helps someone.

--

--