45

When I add the configurations for google analytics to my Android project and build the project I get the following error:

:app:transformClassesWithDexForDebug
UNEXPECTED TOP-LEVEL EXCEPTION:
com.android.dex.DexException: Multiple dex files define Ljavax/inject/Inject;
    at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:596)
    at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:554)
    at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:535)
    at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:171)
    at com.android.dx.merge.DexMerger.merge(DexMerger.java:189)
    at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:502)
    at com.android.dx.command.dexer.Main.runMonoDex(Main.java:334)
    at com.android.dx.command.dexer.Main.run(Main.java:277)
    at com.android.dx.command.dexer.Main.main(Main.java:245)
    at com.android.dx.command.Main.main(Main.java:106)

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:transformClassesWithDexForDebug'.
> com.android.build.transform.api.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk/Contents/Home/bin/java'' finished with non-zero exit value 2

* Try:
Run with --info or --debug option to get more log output.

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformClassesWithDexForDebug'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:64)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:42)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.AbstractTask.executeWithoutThrowingTaskFailure(AbstractTask.java:310)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.executeTask(AbstractTaskPlanExecutor.java:79)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:63)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:51)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:23)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:88)
    at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:37)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62)
    at org.gradle.execution.DefaultBuildExecuter.access$200(DefaultBuildExecuter.java:23)
    at org.gradle.execution.DefaultBuildExecuter$2.proceed(DefaultBuildExecuter.java:68)
    at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:62)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:55)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:149)
    at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:106)
    at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:86)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:90)
    at org.gradle.tooling.internal.provider.runner.BuildModelActionRunner.run(BuildModelActionRunner.java:54)
    at org.gradle.launcher.exec.ChainingBuildActionRunner.run(ChainingBuildActionRunner.java:35)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:41)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:28)
    at org.gradle.launcher.daemon.server.exec.ExecuteBuild.doBuild(ExecuteBuild.java:49)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.WatchForDisconnection.execute(WatchForDisconnection.java:37)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.ResetDeprecationLogger.execute(ResetDeprecationLogger.java:26)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.RequestStopIfSingleUsedDaemon.execute(RequestStopIfSingleUsedDaemon.java:34)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:74)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput$2.call(ForwardClientInput.java:72)
    at org.gradle.util.Swapper.swap(Swapper.java:38)
    at org.gradle.launcher.daemon.server.exec.ForwardClientInput.execute(ForwardClientInput.java:72)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.health.DaemonHealthTracker.execute(DaemonHealthTracker.java:47)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.LogToClient.doBuild(LogToClient.java:66)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.EstablishBuildEnvironment.doBuild(EstablishBuildEnvironment.java:71)
    at org.gradle.launcher.daemon.server.exec.BuildCommandOnly.execute(BuildCommandOnly.java:36)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.health.HintGCAfterBuild.execute(HintGCAfterBuild.java:41)
    at org.gradle.launcher.daemon.server.api.DaemonCommandExecution.proceed(DaemonCommandExecution.java:120)
    at org.gradle.launcher.daemon.server.exec.StartBuildOrRespondWithBusy$1.run(StartBuildOrRespondWithBusy.java:50)
    at org.gradle.launcher.daemon.server.DaemonStateCoordinator$1.run(DaemonStateCoordinator.java:246)
    at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:54)
    at org.gradle.internal.concurrent.StoppableExecutorImpl$1.run(StoppableExecutorImpl.java:40)
Caused by: org.gradle.internal.UncheckedException: com.android.build.transform.api.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk/Contents/Home/bin/java'' finished with non-zero exit value 2
    at org.gradle.internal.UncheckedException.throwAsUncheckedException(UncheckedException.java:45)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:78)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.doExecute(AnnotationProcessingTaskFactory.java:243)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:219)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$IncrementalTaskAction.execute(AnnotationProcessingTaskFactory.java:230)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:208)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61)
    ... 57 more
Caused by: com.android.build.transform.api.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk/Contents/Home/bin/java'' finished with non-zero exit value 2
    at com.android.build.gradle.internal.transforms.DexTransform.transform(DexTransform.java:411)
    at com.android.build.gradle.internal.pipeline.TransformTask.transform(TransformTask.java:112)
    at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:75)
    ... 63 more
Caused by: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk/Contents/Home/bin/java'' finished with non-zero exit value 2
    at com.android.build.gradle.internal.process.GradleProcessResult.assertNormalExitValue(GradleProcessResult.java:42)
    at com.android.builder.core.AndroidBuilder.convertByteCode(AndroidBuilder.java:1325)
    at com.android.build.gradle.internal.transforms.DexTransform.transform(DexTransform.java:396)
    ... 65 more
Caused by: org.gradle.process.internal.ExecException: Process 'command '/Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk/Contents/Home/bin/java'' finished with non-zero exit value 2
    at org.gradle.process.internal.DefaultExecHandle$ExecResultImpl.assertNormalExitValue(DefaultExecHandle.java:365)
    at com.android.build.gradle.internal.process.GradleProcessResult.assertNormalExitValue(GradleProcessResult.java:40)
    ... 67 more

What does this mean and how can I prevent this error?

Michael
  • 32,527
  • 49
  • 210
  • 370

13 Answers13

97

A little late to the game here but this is most likely a problem with the dependencies you have listed in your build.gradle file for you app.

After lots of testing i successfully chased down my problem and believe it could be of help to others.

Things I do not recommend:

Unless you have an absolute need to enable multiDex in your build.gradle DO NOT DO IT, this is just stepping over the underlying problem in your app and not getting to the root of it. You are also unnecessarily increasing the size of your apk, and there could be unexpected crashes when there is a conflicting method in your dex file.

Things to look out for:

Check all your dependencies in your build.gradle file. Are you referencing a dependency that also includes a dependency you have already included? For example, if your including appcompat-v7 there is no need to include appcompat-v4 since v7 includes all features from v4.

WHAT I ACTUALLY FOUND (MY ISSUE causing my app to exceed method limit in my dex file) ----> GOOGLE PLAY SERVICES

If you do not need all the google play services library dependencies STAY AWAY from this line in your build.gradle compile 'com.google.android.gms:play-services:8.3.0' and instead just use what you need!!

Google has a comprehensive list of the libraries for selectively compiling here

With all that said you probably only need to include this one line in gradle for your Google Analytics:

  dependencies{
       compile 'com.google.android.gms:play-services-analytics:8.3.0'
  }

EDIT

Also, you can view the dependency tree by going to the root of your project (or using terminal in Android studio) and running:

./gradlew app:dependencies

Good Luck and happy coding!

Update

Now as of Android Studio 2.2 you no longer need to trial and error whether you need to use multi-dex in your application. Use the Apk Analyzer to see if its really needed!

kandroidj
  • 13,784
  • 5
  • 64
  • 76
13

Explication: Building Apps with Over 65K Methods

Android application (APK) files contain executable bytecode files in the form of Dalvik Executable (DEX) files, which contain the compiled code used to run your app. The Dalvik Executable specification limits the total number of methods that can be referenced within a single DEX file to 65,536, including Android framework methods, library methods, and methods in your own code. Getting past this limit requires that you configure your app build process to generate more than one DEX file, known as a multidex configuration.

Note: This allows you to refer to all methods of the app. It is as if you have two modules (limit: 2 x 65K) but compacted into one. This entails a cost (time) in the build process.

Solution:

  1. You should try to format your code with libraries to remove excess classes and also not exceed the limit methods. For example if you use maps play-services ( com.google.android.gms: play-services: 8.1.0), you can change to (compile 'com.google.android.gms:play-services-maps:8.1.0') to eliminate unnecessary library dependencies. Then Sync Gradle in AndroidStudio and check if it run. If no run go to point 2.
  2. Add this on build.gradle (app module).
android {
   ...
   defaultConfig {
      ...
      multiDexEnabled true
   }
}
SergioLucas
  • 1,094
  • 8
  • 16
  • 1
    I think your problem is that you pass 65k limit. For example if you use maps play-services ( com.google.android.gms: play-services: 8.1.0), you can change to (compile 'com.google.android.gms:play-services-maps:8.1.0') to eliminate unnecessary library dependencies – SergioLucas Oct 01 '15 at 12:12
  • I have done this but the error persists. What else can we do? – Saket Jain Nov 15 '15 at 09:10
5

For me it was related to simplexml converter for retrofit 2. And it fixed by:

compile ("com.squareup.retrofit2:converter-simplexml:2.0.0-beta4"){ exclude module: 'stax' exclude module: 'stax-api' exclude module: 'xpp3'}

Denis Nek
  • 1,874
  • 3
  • 19
  • 21
3

Multidex support for Android 5.0 and higher

Android 5.0 and higher uses a runtime called ART which natively supports loading multiple dex files from application APK files. ART performs pre-compilation at application install time which scans for classes(..N).dex files and compiles them into a single .oat file for execution by the Android device. For more information on the Android 5.0 runtime, see Introducing ART.

That means your app would working fine on API level 21 or above.

Multidex support prior to Android 5.0

Versions of the platform prior to Android 5.0 use the Dalvik runtime for executing app code. By default, Dalvik limits apps to a single classes.dex bytecode file per APK. In order to get around this limitation, you can use the multidex support library, which becomes part of the primary DEX file of your app and then manages access to the additional DEX files and the code they contain.

So, Firstly making sure you have imported correct dependency, which It seems you did it.

dependencies {
  compile 'com.android.support:multidex:1.0.1'
}

In your manifest add the MultiDexApplication class from the multidex support library to the application element.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.multidex.myapplication">
    <application
        ...
        android:name="android.support.multidex.MultiDexApplication">
        ...
    </application>
</manifest>

Alternative to that, If your app extends the Application class, you can override the attachBaseContext() method and call MultiDex.install(this) to enable multidex.

   @Override
protected void attachBaseContext(Context base) {
    super.attachBaseContext(base);
    MultiDex.install(this);
}

Finally, you will need to update your build.gradle file as below by adding multiDexEnabled true :

defaultConfig {  
        applicationId '{Project Name}'  
        minSdkVersion 15  
        targetSdkVersion 23  
        versionCode 1  
        versionName "1.0"  
        multiDexEnabled true  
    }  

I hope it will help you out.

pRaNaY
  • 24,642
  • 24
  • 96
  • 146
Bhavesh Patadiya
  • 25,740
  • 15
  • 81
  • 107
  • 2
    You wrote about ``attachBaseContext`` but in your example you did use ``onCreate``. According to this: https://developer.android.com/reference/android/support/multidex/MultiDexApplication.html it must be ``attachBaseContext``. – Michael Oct 19 '15 at 09:40
2

in my case, I had this twice in the build.grade file

compile 'com.google.android.gms:play-services-auth:8.4.0'

Once I removed the 2nd entry, it worked fine.

techtinkerer
  • 1,280
  • 2
  • 15
  • 26
  • in my case I had an additional 'com.google.android.gms:play-services:8.4.0' which was a left over from something I was trying. Thanks this comment pointed me in right direction. – lazyguy Feb 14 '16 at 00:50
2

Exactly the same problem as I encountered!

I found out that it was due to duplicate dependencies. In build.gradle, one dependency may be already included in others, thus generate conflicts. I removed necessary dependencies and solved my problem.

JohannaX
  • 29
  • 2
  • 1
    Please do not use the answers to say "me too". The accepted answer has already said that duplicate dependencies cause the problem. – OneCricketeer Mar 19 '16 at 20:52
1

What i did to fix this is removed the gradle changes from here (https://developers.google.com/analytics/devguides/collection/android/v4/) then in Android Studio went into 'file/Project Structure' then click into analytics and if the box is checked uncheck it, let gradle sync then check the box again and click the button to sign in. After all this to get your analytics tracker working you just have to copy your actual tracker id into mTracker = analytics.newTracker(<here>) look at this page for help. https://developers.google.com/android/reference/com/google/android/gms/analytics/GoogleAnalytics

Ryan Johnston
  • 228
  • 3
  • 10
1

Include specific dependencies in the build file.

If you want to add maps into your app then include compile 'com.google.android.gms:play-services-location:9.2.1'


instead of compile 'com.google.android.gms:play-services:9.2.1'

Vikas
  • 4,263
  • 1
  • 34
  • 39
0

i think you are using google analytic sdk V3 use V4 instead i have also facing the same issue while using sdk V3 of google analytic https://developers.google.com/analytics/devguides/collection/android/v4/ see this link for more information.

Satyavrat
  • 469
  • 1
  • 7
  • 24
0

This could happen if you updated Android Studio to the latest version 1.4. Did you update the support libraries to the latest versions? Your compileSdkVersion should be 23.

apply plugin: 'com.android.application'

android {
compileSdkVersion 23 //update this to 23
buildToolsVersion "21.1.2"

defaultConfig {
    applicationId "your.package.name"
    minSdkVersion 16
    targetSdkVersion 21
    multiDexEnabled true //enable this
}

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

dependencies {
// update these to 23 if you have them and add the multidex
    compile 'com.android.support:support-v4:23.0.1'
    compile 'com.android.support:appcompat-v7:23.0.1'
    compile 'com.android.support:design:23.0.1'
    compile 'com.google.android.gms:play-services:+'

    compile 'com.android.support:multidex:1.0.1'

}
user2759839
  • 305
  • 1
  • 3
  • 11
0

I actually found that having too many Android Studio modules was contributing to having this error without multidex enabled. If you are trying to avoid enabling multidex the limit seemed to be around 26 modules. This was with Android Studio 1.5.1

0

The same problem but when using react-native-svg. This helped me:

cd android
./gradlew clean

Source

Zdeněk
  • 323
  • 2
  • 9
0

From Android developer website:

Android 5.0 (API level 21) and higher uses a runtime called ART which naively supports loading multiple DEX files from APK files.

I have set the min SDK to 21 and it solved the issue for me (of course you need to check your specific case if setting min-SDK to 21 or greater is fine with you)

Chehadeh
  • 11
  • 2