androidgradleandroid-buildconfig

Is there any chance to keep global variable in global gradle which value can be updated in App modules and utilised in lib modules


I have created multi module project in android studio. which is having 3 app modules and 5 library modules.

I want a constant variable DB_VERSION_CODE in one of library module. and that value should be updated based on the current running application module. Directory structure is

|-> apps
|    -> Application 1
|       - build.gradle
|    -> Application 2
|       - build.gradle
|    -> Application 3
|       - build.gradle
|  
|-> modules
|    -> Lib Module 1
|       - build.gradle
|    -> Lib Module 2
|       - build.gradle
|    -> Lib Module 3
|       - build.gradle
|    -> Lib Module 4
|       - build.gradle
| 
| - build.gradle (global)
| - versions.gradle (global)

In global build.gradle file I'm importing versions.gradle.

versions.gradle:

ext {
   dbVersionCode = -1 //OVERRIDE IN APP GRADLE
}

In the application module's gradle file I'm trying to update it.

Application 1 - build.gradle

android {
     ....

     defaultConfig {
         //Updating Configuration
         rootProject.ext.dbVersionCode = 2001
         ....
     }
     ....
}

Application 2 - build.gradle

android {
     ....

     defaultConfig {
         //Updating Configuration
         rootProject.ext.dbVersionCode = 2002
         ....
     }
     ....
}

Now I'm trying to utilize the same field in one of the library modules, like below

Lib module 2 - build.gradle

android {
     ....

     defaultConfig {
         //Updating Configuration
          buildConfigField 'int', 'DB_VERSION_CODE', "${rootProject.ext.dbVersionCode}"
         ....
     }
     ....
}

Problem is:

this is working fine when I'm trying to run Application 2, but when I run Application 1 the value 2001 is not getting updated in BuildConfig.

thinking that:

gradle is simple considering last project all the time. This is working only when I comment other App modules in settings.gradle.

Please suggest me either any other approach to achieve the same or solution if I miss anything small.

Thanks in advance.


Solution

  • Finally I found the solution to my question.

    the issue is when I'm trying to run on app all modules Gradle script is running because of that the value is getting overridden in last application module. So the value always same.

    this can be avoided by using a flag which need to be mentioned in gradle.properties

    org.gradle.configureondemand=true
    

    with this only selected module and its dependent module's script will gets executed.