Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the right way to define versionName as ext variable in Android build.gradle?

I tried to define versionName as an ext variable to be used in my gradle configuration file app/build.gradle.

ext {
    versionCode = 19
    versionName = "1.2.3"
    ...
}
...
android {
    ...
    defaultConfig {
        ...
        versionCode versionCode
        versionName versionName
    }
    ...
}
...
task updateReleaseMetadata(type:Exec) {
    commandLine 'sh'
    args "MyShellScript.sh", versionName
}
...

It seemed work fine. However my android code failed to retrieve the versionName as following

PackageInfo pi = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
return pi.versionName;  // return null

I think I had not use the gradle in the right way. Any help would be appriciated.

like image 843
firebear Avatar asked Apr 13 '15 03:04

firebear


1 Answers

This is how to set a global variable in Gradle. Use this instead of ext {}

project.ext.set("versionCode", 19)
project.ext.set("versionName", "1.2.3")

Then in your defaultConfig

versionCode project.versionCode
versionName project.versionName
like image 176
Christian Abella Avatar answered Nov 15 '22 05:11

Christian Abella