2

I am developing an android application for fetching two different Rest API for two different Build Variant sharing the same DataSource. I am using product flavor for a build variant. But I don't know how to config the Retrofit portion for selecting different API for different build variant.

Thank in Advance

Neel Patel
  • 21
  • 2
  • Possible duplicate of [Android using Gradle Build flavors in the code like an if case](https://stackoverflow.com/questions/24119557/android-using-gradle-build-flavors-in-the-code-like-an-if-case) – MadLeo Jun 07 '19 at 04:17

2 Answers2

3

You can create a BuildConfig Field to provide different REST API URL based on your product flavors to your API client:

Open your build.gradle (app level) file and add the following lines to your android block:

    android {
        ....
        applicationVariants.all { variant ->
            def variantName = variant.flavorName
            // replace your specific flavor here instead of 'flavor1' & 'flavor2'
            if (variantName.contains("flavor1")) { 
                variant.buildConfigField 'String', "SERVER_URL", '"your_flavor_specific_url_here"'
            } else if (name.contains("flavor2")) {
                variant.buildConfigField 'String', "SERVER_URL", '"your_flavor_specific_url_here"'
            }
        }
        ....
    }

Now Rebuild your project and then you can access BuidConfig.SERVER_URL in your project which will differ based on your product flavor you've selected.

Jeel Vankhede
  • 11,592
  • 2
  • 28
  • 58
0

for debug release, you can use

        // setting up retrofit
        .baseUrl(if (BuildConfig.DEBUG) {
            "https://debug.server"
        } else {
            "https://release.server"

        })

for flavor, you can try

        // setting up retrofit
        .baseUrl(if (BuildConfig.FLAVOR == "test") {
            "https://debug.server"
        } else if(BuildConfig.FLAVOR == "staging"){
            "https://staging.server"
        } else {
            "https://release.server"
        })

This question describes how to define flavors

fangzhzh
  • 2,172
  • 21
  • 25