Android Studio Gradle use variables

When updating my App I would like to store the versionCode and versionName in one place, as it is needed in the Gradle and is visible in the App.

Part of Gradle:

defaultConfig {
    applicationId "my.awesome.app"
    minSdkVersion 19
    targetSdkVersion 23
    versionCode 8
    versionName "1.8.0"
}

Part of strings.xml:

<string name="app_name">My Awesome App</string>
<string name="app_version_code">8</string>
<string name="app_version_name">v.1</string>
<string name="foo_version">8</string>
<string name="bar_version">.0</string>
<string name="version">Version</string>

I already use the strings.xml in the Manifest.xml:

android:versionCode="@string/app_version_code"
android:versionName="@string/app_version_name">

It seems silly to me to have this data in 2 places. How can I get the values from strings.xml into gradle?

Upvotes: 1

Views: 200

Answers (1)

azizbekian
azizbekian

Reputation: 62209

First, you do not need to specify android:versionCode and android:versionName in AndroidManifest.xml if you specify them in build.gradle (you do right?).

Second, the framework would generate a BuildConfig.java class for you, which contains all the info you need in the scope of this question. I assume you need to refer to those values for some reason:

enter image description here

So, you may refer to e.g. version code from anywhere through your code by

BuildConfig.VERSION_CODE;

Upvotes: 3

Related Questions