0

I have 2 product flavors:

productFlavors {
    first{}
    second{}
}

and I have a class Http with constant value like on screen:

enter image description here

My problem is:

If I have set build first, I want Http class with CODE = 2000
but if I have set build second I want Http class with CODE = 1000

I have seen such a project which looked like : repo(first) and after change build repo(second) and class http was different depending on the current build, but can't replicate it :/

Xavier Rubio Jansana
  • 6,388
  • 1
  • 27
  • 50
purcha
  • 371
  • 3
  • 12

2 Answers2

3

If your classes are the same but the only difference is the constant, then you do not need to duplicate the code and all you need to do is create gradle constants that you access via the BuildConfig class:

productFlavors {
    flavor1 {
        buildConfigField 'int', 'CODE', '1000'
    }

    flavor2 {
        buildConfigField 'int', 'CODE', '2000'
    }
}

Then you would use

BuildConfig.CODE

in your HTTP calls, that would hold 1000 or 2000 depending on the flavor.

Francesc
  • 25,014
  • 10
  • 66
  • 84
  • Agree. This would be a better solution than mine for such a simple case. In case you need a more complex solution (e.g. different methods depending on your flavor) then my solution will be the way to go. – Xavier Rubio Jansana Apr 29 '19 at 22:17
0

Create two copies of your Http class, one in src/first/com.androidapp.testproject/repo and the other one in src/second/com.androidapp.testproject/repo, and remove the copy from src/main/....

The first version of your class in src/first/... will get built for your flavor first, and the one in src/second/... will get built for your flavor second. Of course, you have to adjust the value for CODE in the appropriate copy of your classes.

See the following answer for more information https://stackoverflow.com/a/16746755/3286819

Xavier Rubio Jansana
  • 6,388
  • 1
  • 27
  • 50
  • please, could you help me with my question? I have a similar problem, but I'm getting error in second flavor because I'm using android annotation: https://stackoverflow.com/questions/59715835/androidannotation-with-2-productflavors – Ladessa Jan 13 '20 at 12:06
  • 1
    @Ladessa I've just seen your comment and question post. Glad that you figured it out. :) – Xavier Rubio Jansana Jan 14 '20 at 13:07