"Unable to merge dex" 使用房间时

"Unable to merge dex" when using room

我正在尝试将 "room" 添加到我的项目中。

当我尝试构建项目时,出现错误:

Error:Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'. java.lang.RuntimeException: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex

我已经做过的事情:

  1. Clean/Rebuild 项目
  2. 我在 defaultConfig{} 中添加了 "multiDexEnabled true"。然后我得到错误:

    Error:Execution failed for task ':app:transformClassesWithMultidexlistForDebug'. java.io.IOException: Can't write [C:\Users\user1\AndroidStudioProjects\git\mobile\app\build\intermediates\multi-dex\debug\componentClasses.jar] (Can't read [C:\Users\user1.gradle\caches\transforms-1\files-1.1\support-core-utils-26.1.0.aar\a6c34f6784b0b6bc5c2fc7a7815426da\jars\classes.jar(;;;;;;**.class)] (Duplicate zip entry [classes.jar:android/support/v4/content/PermissionChecker$PermissionResult.class]))

如果我从我的项目中删除 "room",它的构建没有错误。

我正在使用 Android Studio 3,gradle 构建工具 3.0.0。

这是我的 build.gradle:

apply plugin: 'com.android.application'
apply plugin: 'me.tatarka.retrolambda'

buildscript {
   repositories {
       mavenCentral()
   }

   dependencies {
       classpath 'me.tatarka:gradle-retrolambda:3.2.5'
   }
}

repositories {
    mavenCentral()
}

android {
   compileSdkVersion 23
   buildToolsVersion '26.0.2'

   defaultConfig {
        applicationId "trsnet.gtp2.com"
        minSdkVersion 17
        targetSdkVersion 23
        multiDexEnabled true
   }

   buildTypes {
       release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 
                'proguard-rules.txt'
       }
   }

   compileOptions {
       sourceCompatibility JavaVersion.VERSION_1_8
       targetCompatibility JavaVersion.VERSION_1_8
   }

}

dependencies {

    compile files('libs/commons-codec-1.9.jar')
    compile files('libs/ksoap2-android-assembly-3.0.0-jar-with-
    dependencies.jar')
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:cardview-v7:23.2.1'
    compile 'com.android.support:appcompat-v7:23.2.1'
    compile 'com.android.support:design:23.2.1'
    compile 'com.android.support.constraint:constraint-layout:+'
    compile 'io.reactivex:rxandroid:1.2.1'
    compile 'io.reactivex:rxjava:1.1.6'
    compile 'com.jakewharton.rxbinding:rxbinding:0.4.0'
    implementation 'android.arch.persistence.room:runtime:1.0.0'
    annotationProcessor 'android.arch.persistence.room:compiler:1.0.0'
}

我也遇到了这个问题,我花了很长时间才解决,但我终于解决了。 ROOM 使用了一些 support-v4 库,所以这就是为什么您会收到重复的 zip 条目错误的原因。在我的情况下,ROOM 使用的组件来自比我需要的更早的版本。所以对我 (found here) 有用的是将以下内容添加到 Gradle 文件的根级别:

configurations {
    all*.exclude group: 'com.android.support', module: 'support-v4'
}

我发现这样做是为了防止库包含任何 support-v4 组件,但是您必须手动包含 ROOM 和您可能需要的任何其他组件的必要组件。如果您需要准确找出哪些库是重复的,那么您可以按照 these instructions 查看每个库及其依赖项。

稍微不相关的注意事项:从 Gradle 3.0 开始,使用 compile 配置已被弃用,应替换为 implementationapi,可以找到一个很好的解释.