82

I have built a new project in Android Studio using the new project templates provided as part of the tool. All of the code has been generated by Studio I have not made any amendments yet.

I am attempting to run the code but the app fails with the following errors, not sure what the problem is so any help appreciated.

UNEXPECTED TOP-LEVEL EXCEPTION:
com.android.dex.DexException: Multiple dex files define Landroid/support/v7/app/ActionBar$Callback;
    at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:594)
    at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:552)
    at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:533)
    at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:170)
    at com.android.dx.merge.DexMerger.merge(DexMerger.java:188)
    at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:439)
    at com.android.dx.command.dexer.Main.runMonoDex(Main.java:287)
    at com.android.dx.command.dexer.Main.run(Main.java:230)
    at com.android.dx.command.dexer.Main.main(Main.java:199)
    at com.android.dx.command.Main.main(Main.java:103)

 FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:dexDebug'.
> com.android.ide.common.internal.LoggedErrorException: Failed to run command:
    C:\Users\RichardKavanagh\AppData\Local\Android\android-sdk\build-tools\19.0.1\dx.bat --dex --output D:\Android\Projects\MyHealthRecord\app\build\libs\app-debug.dex D:\Android\Projects\MyHealthRecord\app\build\classes\debug D:\Android\Projects\MyHealthRecord\app\build\dependency-cache\debug D:\Android\Projects\MyHealthRecord\app\build\pre-dexed\debug\android-support-v7-appcompat-5a78dab7e2789bbe64f4bc80d106ca75c04dcf6f.jar D:\Android\Projects\MyHealthRecord\app\build\pre-dexed\debug\classes-f9b947272e9f33ba50355b52d82755584f9c0c58.jar D:\Android\Projects\MyHealthRecord\app\build\pre-dexed\debug\support-v4-19.0.0-31a2c13df80d37d62ca50fec3bde6da0ca706223.jar
Error Code:
    2
Output:

    UNEXPECTED TOP-LEVEL EXCEPTION:
    com.android.dex.DexException: Multiple dex files define Landroid/support/v7/app/ActionBar$Callback;
        at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:594)
        at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:552)
        at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:533)
        at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:170)
        at com.android.dx.merge.DexMerger.merge(DexMerger.java:188)
        at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:439)
        at com.android.dx.command.dexer.Main.runMonoDex(Main.java:287)
        at com.android.dx.command.dexer.Main.run(Main.java:230)
        at com.android.dx.command.dexer.Main.main(Main.java:199)
        at com.android.dx.command.Main.main(Main.java:103)



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

BUILD FAILED

Total time: 12.948 secs
BENBUN Coder
  • 4,801
  • 7
  • 52
  • 89

14 Answers14

117

Like everyone else said here, the support library (com.android.support) is being included more than once in your project. Try adding this in your build.gradle at the root level and it should exclude the support library from being exported via other project dependencies.

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

If you have more then one support libs included in the dependencies like this, you may want to remove one of them:enter image description here

iTapAndroid
  • 1,875
  • 1
  • 15
  • 12
  • 1
    this is exactly what fixed this issue – andreimarinescu Apr 02 '14 at 14:06
  • @iTapAndroid : I need add to which `build.gradle` file? file in `Module` or `Project` (have this line `classpath 'com.android.tools.build:gradle:0.9.+'`)? Please tell me, I can not fix this. – Huy Tower Apr 23 '14 at 09:27
  • You'd want to add it in your module gradle file. This would be the file where you're adding all your dependencies. – iTapAndroid Apr 24 '14 at 16:30
  • @iTapAndroid If my eclipse project do not have a build.gradle, what can I do so solve this? – Kill Console Jul 02 '14 at 08:55
  • 4
    This just doesn't work for me I have the same issue. When I add the code mentioned I then cannot import android.support.v4.app.ActionBarDrawerToggle; – NathofGod Aug 25 '14 at 15:17
  • @NathofGod please add your full gradle console error message. "Unexpected top level exception" happens because of repeated code, which ends up confusing dex-merger. The code that is repeated in your project might not be coming from support-4 module. – iTapAndroid Aug 25 '14 at 18:17
  • This seems like a sledge hammer approach, right now I have facebook, the maps utils library and my main project all requiring links to the support library and I'm not sure how to set that up. If I use this line, then my main project cannot see the support library I think – Daniel Wilson Sep 08 '14 at 15:44
  • @DanielWilson, this line is specific to the library projects, and any dependencies that you add to your own project would not be affected by this. It IS a sledge hammer approach, because you DON'T want any of the support libraries from dependencies. This might not work where you need libraries exported from dependencies, but that use case isn't in the question here. – iTapAndroid Sep 08 '14 at 20:12
  • Add the smilliar for all*.exclude group: 'com.android.support', module: 'support-annotations' – Code_Life Dec 23 '14 at 04:55
  • I tried and it broke one of the library project `AccountInfoFragment.java:53: error: cannot access FragmentActivity public class AccountInfoFragment extends SherlockFragment implements DataLoadedCallback,DialogInterface.OnClickListener{ ^ class file for android.support.v4.app.FragmentActivity not found` @iTapAndroid – ericn Jan 02 '15 at 06:35
  • @fullMoon, "all" means do the exclusion from ALL the configurations(variants, flavors) of the project. – iTapAndroid Jan 26 '15 at 17:38
  • @IvanV the exception raised here isn't about the method limit. It's a duplicate dex exception. Why are we talking about 65k method limit exception. I think it's misleading. – iTapAndroid Oct 01 '15 at 15:31
18

enter image description here

dependencies {
    compile 'com.android.support:support-v4:19.1.+'
    compile fileTree(dir: 'libs', include: ['*.jar'])
}

This gets conflicted if you have the support jar in your libs folder. If you have the support jar in your project libs folder and you have the module dependency added to compile 'com.android.support:support-v4:13.0.+' the UNEXPECTED_TOPLEVEL_DEPENDANCY exception will be thrown. conflicting folder structure and build.gradle

Jerome
  • 8,427
  • 2
  • 32
  • 41
varunarl
  • 291
  • 3
  • 4
  • Great post, thank you. What did it for me was the `compile fileTree(dir: 'libs', include: ['*.jar'])` part in your screenshot. Commented out all of the individual dependencies and plugged that in and it fixed my problem. – cowsay Oct 14 '14 at 18:04
9

Because you may include two same libs in your project. check your build.gradle file.

dependencies {
    compile 'com.android.support:appcompat-v7:+'
    compile files('libs/android-support-v4.jar') 
 }

if your file includes compile 'com.android.support:appcompat-v7:+' and compile files('libs/android-support-v4.jar'), it will have this problems. delete this sentence: compile files('libs/android-support-v4.jar')

That's how I fix this problem.

buptcoder
  • 2,692
  • 19
  • 22
8

The error occurs when you have the same library/directory included more than once in your build.gradle's dependencies. Ok, let’s say you have an App structure that looks like this:

enter image description here

So you have the main “app” and then you have a bunch of sub-apps/modules/libraries. The libraries are: 1) gene_test_library, 2) genes_nine_old_androids_library, & 3) swipe_list_view_library.

My name is Gene, so that’s why there are all these “gene” libraries.

Inside the build.gradle for “app”, I have:

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:21.0.0'

    compile project(':libraries:gene_test_library')
    //compile project(':libraries:genes_nine_old_androids_library')
    compile project(':libraries:swipe_list_view_library')
}

Inside the build.gradle for gene_test_library, I have nothing:

dependencies {
}

Inside build.gradle for gene_nine_old_androids_library, I have:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.0'
}

Inside build.gradle for swipe_list_view_library, I have:

dependencies {
    compile 'com.nineoldandroids:library:2.4.0+'
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:21.0.0'
}

This line of code “compile fileTree(dir: 'libs', include: ['*.jar'])” just means “hey, look inside the ‘libs’ folder inside this module for any jar files. I do not have anything in the libs folder of any of the modules so you can ignore that line of code.

So let’s say I uncomment out //compile project(':libraries:genes_nine_old_androids_library') In the build.gradle for the “app” module. Then I would get the “UNEXPECTED TOP-LEVEL EXCEPTION:” error. Why is that?

enter image description here

Well, writing //compile project(':libraries:genes_nine_old_androids_library') inside the build.gradle for “app”, is the same as taking the build dependencies of “genes_nine_old_androids_library” module and putting it there. So uncommenting the //compile project(':libraries:genes_nine_old_androids_library') statement, the build.gradle for “app” module becomes:

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:21.0.0'

    compile project(':libraries:gene_test_library')
    ***compile fileTree(dir: 'libs', include: ['*.jar'])***
    ***compile 'com.android.support:appcompat-v7:21.0.0'***
    compile project(':libraries:swipe_list_view_library')
}

Notice how now “compile 'com.android.support:appcompat-v7:21.0.0'” shows up 2x. That’s where the error is coming from.

Gene
  • 10,819
  • 1
  • 66
  • 58
  • 3
    "The error occurs when you have the same library/directory included more than once." This saved my day. – C-- Dec 07 '14 at 19:13
  • @Gene, in `app` you `compile project(':libraries:swipe_list_view_library')`, and swipe_list_view_library also includes appcompat-v7. So, you end up having 2 appcompat-v7 compiled in `app`. Why doesn't this one throw error? – azizbekian Mar 01 '16 at 07:34
  • Um... I wrote this years ago... I think the error it throws is UNEXPECTED TOP-LEVEL EXCEPTION. – Gene Mar 01 '16 at 22:42
5

I found 2 reason for this issue:

  1. Sometimes its because of multiple included libraries. For example you add

    compile 'com.nineoldandroids:library:2.4.0'

in your gradle and add another library that it also use "nineoldandroids" in it's gradle!

  1. As Android Developer Official website said:

If you have built an Android app and received this error, then congratulations, you have a lot of code!

So, why?

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.

Then what should you do?

  • Avoiding the 65K Limit - How?

    1. Review your app's direct and transitive dependencies - Ensure any large library dependency you include in your app is used in a manner that outweighs the amount of code being added to the application. A common anti-pattern is to include a very large library because a few utility methods were useful. Reducing your app code dependencies can often help you avoid the dex reference limit.
    2. Remove unused code with ProGuard - Configure the ProGuard settings for your app to run ProGuard and ensure you have shrinking enabled for release builds. Enabling shrinking ensures you are not shipping unused code with your APKs.
  • Configuring Your App for Multidex with Gradle - How? 1.Change your Gradle build configuration to enable multidex.

put

multiDexEnabled true

in the defaultConfig, buildType, or productFlavor sections of your Gradle build file.

2.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>

Note: If your app uses extends the Application class, you can override the attachBaseContext() method and call MultiDex.install(this) to enable multidex. For more information, see the MultiDexApplication reference documentation.


Also this code may help you:

dexOptions {
    javaMaxHeapSize "4g"
}

Put in your gradle(android{ ... } ).

Hamed Ghadirian
  • 6,159
  • 7
  • 48
  • 67
4

Hi all I had the same issue that was being caused by a duplicate support version 4 file that I had included while trying to get parse integrated. Deleted the extra inclusion from the libs directory and it works fine now!

Doug Ray
  • 165
  • 1
  • 1
  • 12
  • using Maven repository, I had to remove both "compile 'com.android.support:appcompat-v7:23.0.1'" and "compile 'com.android.support:support-v4:23.+'" from dependencies block. – Mahya Oct 08 '15 at 12:47
3

This happens when a library is getting compiled twice (i.e it is added two time). It can be support library or any other, it doesn't matter.
The common case is that you have added a compile statement of a library which is already in your libs/ directory. All the *.jar files are compiled automatically. Thus, adding a compile statement is causing the error. Removing that statement might fix this issue. If this is not applicable then we already have some awesome answers.

sahil shekhawat
  • 1,208
  • 12
  • 14
3

This might be the dumbest answer, but this worked for me :

  • I removed and added all the libraries on my project manually.(One after the other) And voila, it worked.
  • Build -> Rebuild project

Note: No library of mine was compiled twice.

amalBit
  • 12,041
  • 6
  • 77
  • 94
2

Make sure you have downloaded Support Repository to use support library dependency in build.gradle.

enter image description here

If these all are there already installed sync your project with gradle once using the button available.

sync button

Piyush Agarwal
  • 25,608
  • 8
  • 98
  • 111
0

In my case TOP LEVEL EXCEPTION was throw because of a special char in project path. Just closed the project, changed "á" to "a" and reopened the project. Works!

Eneas Gesing
  • 533
  • 7
  • 10
0

Suddenly, without any major change in my project, I too got this error.

All the above did not work for me, since I needed both the support libs V4 and V7.

At the end, because 2 hours ago the project compiled with no problems, I simply told Android Studio to REBUILD the project, and the error was gone.

Zvi
  • 2,354
  • 2
  • 26
  • 37
0

I had similar problem when I tried to build a signed apk for my app.

Strange, it happened only when I wanted to build a release apk, while on debug apk everything worked OK.

Finally, looking on this thread, I checked for support library duplications in build.gradle and removed any duplications but this wasn't enough..

I had to do clean project and only then finally I've got it to work.

Moti Bartov
  • 3,454
  • 33
  • 42
0

I know that the problem was answered, but this could happen again and my solution was a little different from the ones that I found. In my case the solution wasn't related to include two different libraries in my project. See code below:

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
}

This code was giving that error "Unexpected Top-Level Exception". I fix the code making the following changes:

compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_7
    targetCompatibility JavaVersion.VERSION_1_7
}
Álisson Morais
  • 356
  • 2
  • 19
0

I solved my problem with adding these in build gradle:

   defaultConfig {
   multiDexEnabled true


 dependencies {
 compile 'com.android.support:multidex:1.0.0'

another solution can be removing unnecessary libraries

Bishnu Dudhraj
  • 277
  • 2
  • 7
  • 22
  • Why did you enable multidex? – IgorGanapolsky Jul 17 '17 at 15:24
  • 1
    @IgorGanapolsky its because to solve the issues like above of multiple included libraries. In android studio : 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. – Bishnu Dudhraj Sep 15 '17 at 18:21