Environment variables, BuildConfig, Gradle.properties and Android Studio

Hello guys,

Today I will post some simple steps to have some environment variables in your android studio project. So, if you have some confidential data to use in your android tests, you can hide the password, username or if you just want to have some environment variables separated from your project, just follow these steps:

So, let’s start:

Screen Shot 2015-09-17 at 21.58.28

  • In your gradle.properties create the environment variables (You can find this file inside of your Android Studio project or in your /Users/Your Username/.gradle)
testUsername="username"
testPassword="password"
  • In your build.gradle file (Remember, you can have many build.gradle file, so first try to find the one that you want to share with all projects or the one which you will use only in your project > buildTypes > debug, as it is showed in the structure below). The “USERNAME” and “PASSWORD” will be the variables in your code and the testUsername and testPassword should be the same variable which you are using in your gradle.properties file (above).
android {
buildTypes {
  debug {
    ...
    buildConfigField "String", "USERNAME", testUsername
    buildConfigField "String", "PASSWORD", testPassword
   }

  release {
   ...
    }
  }
}
  • After this, you need to sync your gradle.
  • And in your code, just call the variables like this:
BuildConfig.USERNAME
BuildConfig.PASSWORD

I am using gradle 2.4 and androidStudio 1.3.2.

Thank you, see you next week 🙂

Resources:

http://examples.javacodegeeks.com/core-java/gradle/gradle-properties-build-configuration-example/

http://www.rainbowbreeze.it/environmental-variables-api-key-and-secret-buildconfig-and-android-studio/