Android gradle.properties to build.gradle to BuildConfig

In this post, we will go through the steps for adding custom properties in gradle.properties, retrieve them in the build.gradle and make it available in the BuildConfig file.

Create a file under app/ folder and name it gradle.properties with the following sample properties.

#We can define variables here and retrive it in the build.gradle
apiId=abcdefg
apiPassword=123456789

Open the app build.gradle file, inside the defaultConfig tag, add the following. These two lines will generate two properties in the BuildConfig file.

buildConfigField "String", "API_ID", "\"${project.apiId}\""
buildConfigField "String", "API_PASSWORD", "\"${project.apiPassword}\""

Click sync now, and then open the generated file BuildConfig.java, you will see these properties added in the BuildConfig file.

// Fields from default config.
public static final String API_ID = "abcdefg";
public static final String API_PASSWORD = "123456789";

Now we can access the apid id and api password in the app code from BuildConfig.

Why do we want to go through all these trouble to get api id and api password, why not just put in the in a constants file in the first place? We want to do this when we don’t want to commit the id and password into the code. This way, we can leave the gradle.properties out of the source control and only make it available locally.

Another way to store the id and password is to set them as environment variables and retrieve them like this in the build.gradle.

buildConfigField "String", "API_ID", "\"${System.getenv("API_ID")}\""
buildConfigField "String", "API_PASSWORD", "\"${System.getenv("API_PASSWORD")}\""

Complete example in Github

Search within Codexpedia

Custom Search

Search the entire web

Custom Search