Programing

Android Studio-예상치 못한 최상위 예외 :

lottogame 2020. 10. 5. 07:31
반응형

Android Studio-예상치 못한 최상위 예외 :


도구의 일부로 제공된 새 프로젝트 템플릿을 사용하여 Android Studio에서 새 프로젝트를 빌드했습니다. 모든 코드는 Studio에서 생성되었으며 아직 수정하지 않았습니다.

코드를 실행하려고하는데 앱이 다음과 같은 오류로 실패하고 문제가 무엇인지 확실하지 않으므로 도움을 주시면 감사하겠습니다.

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

다른 사람들이 여기에서 말한 것처럼 지원 라이브러리 ( com.android.support)가 프로젝트에 두 번 이상 포함됩니다. build.gradle이를 루트 수준에서 추가 하면 지원 라이브러리가 다른 프로젝트 종속성을 통해 내보내지지 않도록 제외해야합니다.

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

이와 같은 종속성에 하나 이상의 지원 라이브러리가 포함되어있는 경우 다음 중 하나를 제거 할 수 있습니다.여기에 이미지 설명 입력


여기에 이미지 설명 입력

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

libs 폴더에 support jar가 있으면 충돌이 발생합니다. 프로젝트 libs 폴더에 지원 jar가 있고 'com.android.support:support-v4:13.0.+'컴파일에 모듈 종속성이 추가 된 경우 UNEXPECTED_TOPLEVEL_DEPENDANCY 예외가 발생합니다.충돌하는 폴더 구조 및 build.gradle


프로젝트에 두 개의 동일한 라이브러리를 포함 할 수 있기 때문입니다. build.gradle 파일을 확인하십시오.

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

컴파일 파일이 포함되어있는 경우 'com.android.support:appcompat-v7:+'compile files('libs/android-support-v4.jar'),이 문제가됩니다. 이 문장을 삭제하세요 : compile files ( 'libs / android-support-v4.jar')

이것이 제가이 문제를 해결하는 방법입니다.


이 오류는 build.gradle의 종속성에 동일한 라이브러리 / 디렉토리가 두 번 이상 포함 된 경우 발생합니다. 예, 다음과 같은 앱 구조가 있다고 가정 해 보겠습니다.

여기에 이미지 설명 입력

따라서 기본 "앱"이 있고 하위 앱 / 모듈 / 라이브러리가 많이 있습니다. 라이브러리는 1) gene_test_library, 2) genes_nine_old_androids_library, 3) swipe_list_view_library입니다.

제 이름은 Gene입니다. 그래서 이러한 "유전자"라이브러리가 모두 있습니다.

"app"의 build.gradle 안에 다음이 있습니다.

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')
}

gene_test_library의 build.gradle 안에는 아무것도 없습니다.

dependencies {
}

gene_nine_old_androids_library의 build.gradle 안에 다음이 있습니다.

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

swipe_list_view_library의 build.gradle 내부에는 다음이 있습니다.

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

이 코드 줄은 "compile fileTree (dir : 'libs', include : [ '* .jar'])"는 단지 "야,이 모듈 내의 'libs'폴더에서 jar 파일을 찾아보십시오. 모듈의 libs 폴더에 아무것도 없으므로 해당 코드 줄을 무시할 수 있습니다.

따라서 "app"모듈의 build.gradle에서 // compile project ( ': libraries : genes_nine_old_androids_library') 주석 처리를 제거한다고 가정 해 보겠습니다. 그런 다음 "예기치 않은 최상위 예외 :"오류가 발생합니다. 왜 그런 겁니까?

여기에 이미지 설명 입력

"app"에 대한 build.gradle 내부에 // compile project ( ': libraries : genes_nine_old_androids_library')를 작성하는 것은 "genes_nine_old_androids_library"모듈의 빌드 종속성을 가져와 여기에 넣는 것과 같습니다. 따라서 // compile project ( ': libraries : genes_nine_old_androids_library') 문을 주석 해제하면 "app"모듈에 대한 build.gradle은 다음과 같습니다.

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')
}

이제 'compile'com.android.support:appcompat-v7:21.0.0 ''이 2x로 표시되는지 확인하세요. 그것이 오류가 발생하는 곳입니다.


이 문제에 대한 두 가지 이유를 찾았습니다.

  1. 때로는 여러 라이브러리가 포함되어 있기 때문입니다. 예를 들어

    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{ ... } ).


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!


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.


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.


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

여기에 이미지 설명 입력

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

동기화 버튼


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!


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.


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.


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
}

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

참고URL : https://stackoverflow.com/questions/21102598/android-studio-unexpected-top-level-exception

반응형