Create different values for Debug and Release with Gradle

Sometimes it may happen that you want to have different values in your app for debug and release versions. Of course, you can define it in code and change it yourself but this can become tiring, and cause you to make fatal errors when you forget to switch this values properly.

With Gradle you can do this in very elegant way. Let’s say we want to use some BASE_URL with one url address for testing it when we in debug mode, and a different value when we in release mode. We will define it in the build.gradle file:

android {

    buildTypes {
        debug {
            buildConfigField "String", "BASE_URL", "\"http://192.168.0.129:8090/\""
        }

        release {
            buildConfigField "String", "BASE_URL", "\"http://www.thedroidboy.com/\""
            //rest of code
        }
    }
}

Now we can use this value in our code as gradle will produce a class in our package called BuildConfig.class and we can access its values everywhere in our code:

String APP_BASE_URL = BuildConfig.BASE_URL;

The proper values will be injected based on our build type.

Leave a Reply

Your email address will not be published. Required fields are marked *