Debug dependency resolution errors

When you add a dependency, you might encounter issues with dependencies required by the original dependency, and conflicts among different dependency versions. Here's how to analyze your dependency graph and fix common issues that arise.

For guidance on fixing dependency resolution errors that involve custom build logic, see Custom dependency resolution strategies.

View module dependencies

Some direct dependencies may have dependencies of their own. These are called transitive dependencies. Rather than requiring you to manually declare each transitive dependency, Gradle automatically gathers and adds them for you. The Android Gradle plugin provides a task that displays a list of the dependencies Gradle resolves for a given module.

For each module, the report also groups the dependencies based on build variant, testing source set, and classpath. The following is sample report for an app module's runtime classpath of its debug build variant and compile classpath of its instrumented test source set.

debugRuntimeClasspath - Dependencies for runtime/packaging
+--- :mylibrary (variant: debug)
+--- com.google.android.material:material:1.0.0@aar
+--- androidx.appcompat:appcompat:1.0.2@aar
+--- androidx.constraintlayout:constraintlayout:1.1.3@aar
+--- androidx.fragment:fragment:1.0.0@aar
+--- androidx.vectordrawable:vectordrawable-animated:1.0.0@aar
+--- androidx.recyclerview:recyclerview:1.0.0@aar
+--- androidx.legacy:legacy-support-core-ui:1.0.0@aar
...

debugAndroidTest
debugAndroidTestCompileClasspath - Dependencies for compilation
+--- androidx.test.ext:junit:1.1.0@aar
+--- androidx.test.espresso:espresso-core:3.1.1@aar
+--- androidx.test:runner:1.1.1@aar
+--- junit:junit:4.12@jar
...

To run the task, proceed as follows:

  1. Select View > Tool Windows > Gradle (or click Gradle in the tool windows bar).
  2. Expand AppName > Tasks > android and double-click androidDependencies. After Gradle executes the task, the Run window should open to display the output.

For more information about managing dependencies in Gradle, see Dependency management basics in the Gradle User Guide.

Modify dependency metadata

As an app grows in scope, it can contain a number of dependencies including direct dependencies and transitive dependencies (libraries which your app's imported libraries depend on).

There are many ways in which dependencies' metadata can cause issues for your app, either at build time or, even worse, runtime. Similarly, there are many ways to modify or "fix" the metadata to mitigate the problems.

Fix the upstream issue

Perhaps the most robust solution is to fix the issue at its source. For example, imagine there's a dependency you rely on that includes "broken" metadata, such as declaring a dependency that doesn't exist. Ideally, the owner of that library would fix the problem and publish a new version without the issue. If that library is open source and you can file an issue (and one doesn't already exist for this problem), you should create one.

Fix the metadata locally with a component metadata rule

Either as an interim fix while waiting for an upstream fix, or a permanent solution when upstream fixes are infeasible, you can create and apply a ComponentMetadataRule. These rules are flexible and powerful. See the following example of using a rule to remove a transitive dependency that shouldn't be present.

Kotlin

@CacheableRule
abstract class SomeLibraryRule : ComponentMetadataRule {

  override fun execute(context: ComponentMetadataContext) {
    context.details.allVariants {
      withDependencies {
        removeAll { it.group == "com.example.imgtools" && it.name == "native" }
      }
    }
  }
}

dependencyResolutionManagement {
  components {
    withModule("com.android.tools.build:gradle-api")
  }
}

Groovy

@CacheableRule
abstract class SomeLibraryRule implements ComponentMetadataRule {

  void execute(ComponentMetadataContext context) {
    context.details.allVariants {
      withDependencies {
        removeAll { it.group == "com.example.imgtools" && it.name == "native" }
      }
    }
  }
}

dependencyResolutionManagement {
  components {
    withModule("com.android.tools.build:gradle-api", SomeLibraryRule)
  }
}

For more information about component metadata rules, see Modifying Dependency Metadata in the Gradle User Guide.

Fix the metadata locally with an exclude

To quickly verify that removing a transitive dependency solves the problem, you can use an exclude statement. While excludes are helpful for testing, they're less robust and flexible, and thus not recommended as a long-term fix. When following this approach, the exclude needs to be specified each time the dependency in question is declared, which is fragile as it's prone to copy-paste failures. Furthermore, if your exclude has a typo, it will silently do nothing, making it even more error-prone.

To exclude transitive dependencies that you no longer need, you can use the exclude keyword as given below:

Kotlin

dependencies {
    implementation(libs.some.library) {
        exclude(group = "com.example.imgtools", module = "native")
    }
}

Groovy

dependencies {
    implementation(libs.some.library) {
        exclude group: 'com.example.imgtools', module: 'native'
    }
}

Exclude transitive dependencies from test configurations

If you need to exclude certain transitive dependencies from your tests, the code sample shown above might not work as expected. That's because a test configuration (e.g., androidTestImplementation) extends the module's implementation configuration. That is, it always contains implementation dependencies when Gradle resolves the configuration.

So, to exclude transitive dependencies from your tests, you can do as shown below:

Kotlin

import com.android.build.api.variant.HasUnitTest

androidComponents {
  onVariants(selector().all()) { variant ->
    val testComponent = (variant as HasUnitTest).unitTest
    testComponent?.compileConfiguration?.exclude(group = "com.example.library", module = "library")
    testComponent?.runtimeConfiguration?.exclude(group = "com.example.library", module = "library")
  }
}

Groovy

import com.android.build.api.variant.HasUnitTest

androidComponents {
  onVariants(selector().all()) { variant ->
    def testComponent = (variant as HasUnitTest).unitTest
    testComponent?.compileConfiguration?.exclude(group: "com.example.library", module: "library")
    testComponent?.runtimeConfiguration?.exclude(group: "com.example.library", module: "library")
  }
}

Note: You can still use the exclude keyword in the dependencies block as shown in the original code sample from the Exclude transitive dependencies section to omit transitive dependencies that are specific to the test configuration and are not included in other configurations.

Exclude dependencies from any configuration

The way we exclude transitive dependencies from tests can be generalized. You might find yourself in a situation where you need to exclude a dependency from a configuration (classpath), but also multiple dependencies are trying to contribute it transitively. For example, you don't want any test-related dependencies on your main classpaths. If the transitive dependencies are coming from libraries you don't control, your only solution might be to exclude it in your build scripts or build-logic.

Kotlin

androidComponents {
  onVariants(selector().all()) { variant ->
    variant.compileConfiguration.exclude(group = "junit", module = "junit")
    variant.runtimeConfiguration.exclude(group = "junit", module = "junit")
  }
}

Groovy

androidComponents {
  onVariants(selector().all()) { variant ->
    variant.compileConfiguration.exclude(group: "junit", module: "junit")
    variant.runtimeConfiguration.exclude(group: "junit", module: "junit")
  }
}

Fail the build when a forbidden dependency is present

When you own the offending libraries, you should fail the build early so you can fix the upstream libraries, rather than "patch" them downstream in every consumer's build script.

Kotlin

dependencies {
  constraints {
    api("junit:junit") {
      version {
        rejectAll()
      }
    }
  }
}

Groovy

dependencies {
  constraints {
    api("junit:junit") {
      version {
        rejectAll()
      }
    }
  }
}

With this code, your build will fail fast when it tries to resolve any version of the junit:junit library. That error will look like this:

> Could not resolve all files for configuration ':mylib:debugUnitTestRuntimeClasspath'.
   > Could not resolve junit:junit:4.13.2.
     Required by:
         project ':mylib'
         project ':mylib' > project ':anotherlib'
         project ':mylib' > com.google.dagger:hilt-android-testing:2.59.2
         project ':mylib' > org.junit.vintage:junit-vintage-engine:6.1.0
      > Module 'junit:junit' has been rejected:
           Dependency path: 'project ':mylib'' (debugUnitTestRuntimeClasspath) --> 'junit:junit:4.13.2'
           Constraint path: 'project ':mylib'' (debugUnitTestRuntimeClasspath) --> 'project ':mylib'' (debugRuntimeElements) --> 'junit:junit:{reject all versions}'
           Dependency path: 'project ':mylib'' (debugUnitTestRuntimeClasspath) --> 'com.google.dagger:hilt-android-testing:2.59.2' (runtime) --> 'junit:junit:4.13.2'
           Dependency path: 'project ':mylib'' (debugUnitTestRuntimeClasspath) --> 'project ':anotherlib'' (runtimeElements) --> 'junit:junit:4.13.2'
           Dependency path: 'project ':mylib'' (debugUnitTestRuntimeClasspath) --> 'org.junit.vintage:junit-vintage-engine:6.1.0' (runtimeElements) --> 'junit:junit:4.13.2'

For more information, see Declaring Versions and Ranges in the Gradle User Guide.

Fix dependency resolution errors

When you add multiple dependencies to your app project, those direct and transitive dependencies might conflict with one another. The Android Gradle plugin tries to resolve these conflicts gracefully, but some conflicts may lead to compile time or runtime errors.

To help you investigate which dependencies are contributing to errors, inspect your app's dependency tree and look for dependencies that appear more than once or with conflicting versions.

If you can't easily identify the duplicate dependency, try using Android Studio's UI to search for dependencies that include the duplicate class as follows:

  1. Select Navigate > Class from the menu bar.
  2. In the pop-up search dialog, make sure that the box next to Include non-project items is checked.
  3. Type the name of the class that appears in the build error.
  4. Inspect the results for the dependencies that include the class.

The following sections describe the different types of dependency resolution errors you may encounter and how to fix them.

Fix duplicate class errors

If a class appears more than once on the runtime classpath, you get an error similar to the following:

Program type already present com.example.MyClass

This error typically occurs due to one of the following circumstances:

  • A binary dependency includes a library that your app also includes as a direct dependency. For example, your app declares a direct dependency on Library A and Library B, but Library A already includes Library B in its binary.
    • To resolve this issue, remove Library B as a direct dependency.
  • Your app has a local binary dependency and a remote binary dependency on the same library.
    • To resolve this issue, remove one of the binary dependencies.

Fix conflicts between classpaths

Classpaths (represented by the Configuration type in Gradle) are generally independent by default. That is, each classpath is resolved separately and independently, though they can have relationships with one another. For example, the implementation configuration is an extension of the api configuration. The runtime classpath (which is modeled by the runtimeClasspath configuration) extends from the implementation and runtimeOnly configurations. Likewise, the compile classpath is an extension of the implementation and compileOnly configurations.

Because of this separation, each classpath (or configuration) is "resolved" separately, which means it's possible, even likely, that each classpath will resolve different versions of any given library that your app depends on. Practically speaking, your compile classpath might be very different from your runtime classpath, and both will be different from your test compile and runtime classpaths. These conflicts can lead to compilation failures or runtime crashes, with or without test failures giving you any sign of trouble.

Your app's runtime classpath also determines the version numbers that Gradle requires for matching dependencies in the runtime classpath for the app's test APK.

A conflict where different versions of the same dependency appears across multiple classpaths might occur when, for example, your app includes a version of a dependency using the implementation dependency configuration and a library module includes a different version of the dependency using the runtimeOnly configuration.

When resolving dependencies on your runtime and compile time classpaths, Android Gradle plugin 3.3.0 through 8.13.2 attempt to automatically fix certain downstream version conflicts by constraining the compile classpath to be consistent with the runtime classpath. For example, if the runtime classpath includes Library A version 2.0 and the compile classpath includes Library A version 1.0, the plugin automatically updates the dependency on the compile classpath to Library A version 2.0 to avoid errors.

The previous behavior can be reenabled by setting android.dependency.useConstraints=true in your gradle.properties file. See the AGP 9.0.0 release notes for more information.

Consistent resolution within a module

When libraries are resolving inconsistently within a module's classpaths, one solution is the Configuration.shouldResolveConsistentlyWith API. You can use this to, for example, ensure that your compile classpath is consistent with your runtime classpath.

Kotlin

androidComponents {
  onVariants(selector().all()) { variant ->
    variant.compileConfiguration.shouldResolveConsistentlyWith(variant.runtimeConfiguration)
  }
}

Groovy

androidComponents {
  onVariants(selector().all()) { variant ->
    variant.compileConfiguration.shouldResolveConsistentlyWith(variant.runtimeConfiguration)
  }
}

With this code, whenever Gradle resolves the compile classpath, it will also resolve the runtime classpath and constrain your compile time to be consistent with your runtime. Since your runtime is what you ship to consumers, this can be a sensible approach. However, platforms are almost certainly a better choice.

Global consistent resolution

Another approach to the inconsistent resolution problem which can be helpful in larger projects is to create your own platform using Gradle's java-platform plugin.

For example, create a platform/build.gradle.kts (or platform/build.gradle) file like the following:

Kotlin

plugins {
  id("java-platform")
}

javaPlatform {
  allowDependencies()
}

dependencies {
  // Other platforms
  api(platform(libs.androidx.compose.bom))
  api(platform(libs.kotlinx.coroutines.bom))

  // Non-platform dependencies whose versions we want to constrain
  constraints {
    api(libs.foo)
    api(libs.bar)
    …
  }
}

Groovy

plugins {
  id 'java-platform'
}

javaPlatform {
  allowDependencies()
}

dependencies {
  // Other platforms
  api platform(libs.androidx.compose.bom)
  api platform(libs.kotlinx.coroutines.bom)

  // Non-platform dependencies whose versions we want to constrain
  constraints {
    api libs.foo
    api libs.bar
    …
  }
}

And create a consumer/build.gradle.kts (or consumer/build.gradle) file like the following:

Kotlin

dependencies {
  implementation(platform(project(":platform")))
  testImplementation(platform(project(":platform")))
  androidTestImplementation(platform(project(":platform")))
}

Groovy

dependencies {
  implementation platform(project(':platform'))
  testImplementation platform(project(':platform'))
  androidTestImplementation platform(project(':platform'))
}

With this configuration, you can add your :platform project as a platform dependency in each of your modules, which helps ensure that all of your modules have the same version constraints everywhere. If your platform also depends on other platforms, such as the AndroidX Compose BOM, then you have centralized all your platforms and eased maintenance, in addition to solving the version conflict problem.