devrocca
devrocca

Reputation: 2547

How to compile with gradle different dependency module's dependencies based on build variants?

I have an Android app which has a module dependency. This module itself has a jar library as a dependency that comes in two variants, each relative to a build variant of the main app. When I switch build variant in the main app, I managed to automatically select the module's build variant which picks the correct jar, but this is not reflected in the code, where the specific classes from the jar are not found in the build variant specific code.

Here's the related code from the build.gradle files of the main app and the dependency module:

main app - build.gradle

buildTypes {
    type1 {initWith(debug)}
    type2 {initWith(debug)}
}

productFlavors {
    live{}
    test{}
}

dependencies {
    type1Compile project(path: ':module', configuration: 'one')
    type2Compile project(path: ':module', configuration: 'two')
}

module - build.gradle

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    useLibrary 'org.apache.http.legacy'
    publishNonDefault true

defaultConfig {
    minSdkVersion 14
    targetSdkVersion 22
}

buildTypes {
    release {
        minifyEnabled = false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 
            'proguard-rules.pro'
    }
    one {initWith(release)}
    two {initWith(release)}
}
}

dependencies {
    oneCompile files('libs/versionOne/mylib.jar')
    twoCompile files('libs/versionTwo/mylib.jar')
}

So, when I build testType1 variant, Android Studio automatically selects one variant, and with a clean build it all goes fine. But if I switch to testType2, although module's two variant is selected, the editor will highlight missing classes and methods.

How can I make gradle pick the right jar when I switch between the app's build variants?

Some considerations: The module needs the library, since it uses a few classes that are common between the 2 versions. I know this may look like bad project design, but it's an app that has been built by different people in different times, and I now have to develop it "as is".

Upvotes: 3

Views: 1438

Answers (1)

devrocca
devrocca

Reputation: 2547

After some tinkering, I found some clues. First of all, my two jars where the same name, in different folders. After renaming the jars to have also different names, gradle manages to pick the correct one after the build variant switch, provided that an additional "Sync project with gradle files" is done. So now it's not immediate, but eventually it's working.

Upvotes: 0

Related Questions