While the answer above is okay, IMO it's not the best way to go about it. Generally speaking, you want your version name and code stored somewhere outside of the build.gradle file. Very often we do that so we can easily access it from the outside of the app, or to update it automatically for CI systems, etc.
A very simple example: You can put those in the gradle.properties file, like so:
<!-- add to the end of the file: -->
VERSION_NAME=0.0.1
VERSION_CODE=1
Then you can simply access them in any build.gradle via properties object, and add them to BuildConfig like so (note: they will only become available after a successful build):
// build.gradle file of the chosen module
def versionName = properties["VERSION_NAME"]
def versionCode = properties["VERSION_CODE"]
buildTypes.all {
buildConfigField "String", "VERSION_NAME", "\"$versionName\"" // Escaping quote marks to convert property to String
buildConfigField "int", "VERSION_CODE", "$versionCode"
}
Alternatively, you can put those in a dedicated version.properties file. Then you can do the same like this:
def versionProps = loadPropertiesFile(project.file('version.properties'))
buildTypes.all {
buildConfigField "String", "VERSION_NAME", getPropEscaped("VERSION_NAME", versionProps)
buildConfigField "int", "VERSION_CODE", getProp("VERSION_CODE", versionProps)
}