# Automatically increment versionCode when building production APKs

*2018-11-08*

> Automatically increment an Android app’s versionCode for release APK builds using Gradle and a version.properties file.

I use [Fabric](https://www.fabric.io) to monitor app statistics such as _Time in App per User_ and its [Beta](http://try.crashlytics.com/beta/) platform to distribute test builds. Manually incrementing the APK's [`versionCode`](https://developer.android.com/studio/publish/versioning) for each build has become tedious.

I decided to simplify things by letting Gradle automatically increment `versionCode` when building release APKs.

Our implementation uses a properties file named `version.properties` in the app module's root directory, alongside `build.gradle`.

The file contains two properties: `VERSION_NAME`, which defines a version name such as `2.3`, and `VERSION_CODE`, which defines a version code such as `19`.

```ini
VERSION_NAME=2.3
VERSION_CODE=19
```

Next, open the app module's `build.gradle` file:

{{< figure align="aligncenter" width=474 src="/wp-content/uploads/2018/11/Screenshot-2018-11-08-at-14.40.54.png" alt="" caption="" >}}

Define a function to retrieve these values from the properties file and increment `VERSION_CODE` when a release build is requested:

```groovy
/**
 * Gets a value from the 'version.properties' file.
 * @param varName the name of the property to retrieve.
 * @return the property value.
 */
def getVersionPropertiesValue(def varName)
{
    def propertiesFile = file('version.properties')

    if(!propertiesFile.canRead()) {
        throw new GradleException("Could not read " + propertiesFile.name)
    }

    Properties properties = new Properties();
    properties.load(new FileInputStream(propertiesFile))

    def propertyValue = properties[varName]
    if(varName == 'VERSION_CODE')
    {
        // Increment the version code when building a release.
        List gradleTasksNames = gradle.startParameter.getTaskNames();
        for(String taskName : gradleTasksNames)
        {
            if(taskName.contains("Release"))
            {
                propertyValue = propertyValue.toInteger() + 1
                properties[varName] = propertyValue.toString()
                properties.store(propertiesFile.newWriter(), null)
                break
            }
        }
    }

    return propertyValue
}
```

In the Gradle build script's `defaultConfig` block, we'll call this function to retrieve the app's `versionName` and `versionCode` values:

```groovy
android {
    compileSdkVersion 28

    defaultConfig {
        applicationId "com.example.foo"
        versionCode Integer.valueOf(getVersionPropertiesValue('VERSION_CODE'))
        versionName getVersionPropertiesValue('VERSION_NAME')
        minSdkVersion 14
        targetSdkVersion 28
    }
}
```

Now, each time a release build is requested, the version code will increment automatically. To change the version name, update the `VERSION_NAME` property.

