java - Android gives error "Cannot fit requested classes in a single dex file"

java - Android gives error "Cannot fit requested classes in a single dex file"

Winnie Zubin Author: Winnie Zubin Date: 2022-08-17
java - Android gives error "Cannot fit requested classes in a single dex file"

All you need to know about java - Android gives error "Cannot fit requested classes in a single dex file" , in addintion to android - Error : Cannot fit requested classes in a single dex file (# methods: 65978 > 65536) , android - Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536 , android - D8: Cannot fit requested classes in a single dex file , android - NativeScript - Cannot fit requested classes in a single dex file

  1. java - Android gives error "Cannot fit requested classes in a single dex file"
  2. Question:

    I don't know why but it's impossible to launch my app on my mobile this morning. I get this error message:

    Cannot fit requested classes in a single dex file. Try supplying a main-dex list.

    # methods: 68061 > 65536 Message{kind=ERROR, text=Cannot fit requested classes in a single dex file. Try supplying a main-dex list.

    # methods: 68061 > 65536, sources=[Unknown source file], tool

    I'm really new to Android and I don't understand the problem and what I need to do? And why I get this problem now and not before?


    Solution 1:

    In root build.gradle file do something like:

    dependencies {
    
        // ...
    
        implementation 'androidx.multidex:multidex:2.0.1'
    }
    
    android {
        defaultConfig {
    
            // ...
    
            multiDexEnabled true
        }
    }
    

    More details here: Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536

    Solution 2:

    Running RN 0.62 and this worked for me with successful build.

    Update build.gradle enter image description here

    classpath('com.android.support:multidex:1.0.3')

    Update defaultConfig

    enter image description here

    multiDexEnabled true

    After those 2 changes, restart the gradle build again.

    Solution 3:

    Multidex is not always the solution to the problem, is true that it will generate more dex files to fit your method count, but be sure to not import more methods that you need because this in long term will make your builds slower than before.

    For example, if you just need to use the location library from play services, you have two options

    First one is implementing the whole play-services libraries that will come with location

    implementation 'com.google.android.gms:play-services:11.8.0'
    

    These whole libraries could have more than 40.000+ methods (is only an estimative, I don't really know the total count), being close to reaching the 65536 limit methods.

    Instead you should be targeting only the libraries you will use instead of the whole bundle of libraries

    in this case

    implementation 'com.google.android.gms:play-services-location:11.8.0'
    

    could have just 50 - 100 methods to work with, which will be better at build time than loading a whole bunch of methods from the whole library package that you won't ever use.

    this is just a tip to avoid getting

    Cannot fit requested classes in a single dex file.

    For minSdkVersion above android 5.0 API 20 +

    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.

    If you are targeting lower devices (Android 4.1 API 16) or before Android 5 (API 20)

    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.

    You will need to use multidex in this last case

  3. android - Error : Cannot fit requested classes in a single dex file (# methods: 65978 > 65536)
  4. Question:

    hi Guys Im getting This errer when i tried to run my application . i investgated the issue and i found that the problem happen only when i add this google implementation . when i removed the implementaion the app worked just fine . why is that happening and what it is the solution

    implementation 'com.google.android.gms:play-services-auth:20.1.0'

    i dont know where the the cause of the probleme can any one help me by gaving me the solution or dercting me to any article


    Solution 1:

    You must add the library in the app gradle :

    implementation 'com.android.support:multidex:1.0.3'
    

    After, add in the defaultConfig of the app gradle :

    multiDexEnabled true
    

  5. android - Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536
  6. Question:

    I want to add fused location services but it shows me some error. Help me.

    apply plugin: 'com.android.application'
    
    android {
        compileSdkVersion 26
        buildToolsVersion "27.0.1"
        defaultConfig {
            applicationId "com.example.adil.bloodbankapplication"
            minSdkVersion 15
            targetSdkVersion 26
            versionCode 1
            versionName "1.0"
            testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        }
        buildTypes {
            release {
                minifyEnabled false
                proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            }
        }
    }
    
    dependencies {
        compile fileTree(include: ['*.jar'], dir: 'libs')
        compile 'com.android.support:appcompat-v7:26.1.0'
        compile 'com.android.support.constraint:constraint-layout:1.0.2'
        compile 'com.google.firebase:firebase-auth:11.8.0'
        compile 'com.google.firebase:firebase-database:11.8.0'
        compile 'com.android.support:support-v4:26.1.0'
        compile 'junit:junit:4.12'
        compile 'com.android.support:design:26.1.0'
        compile 'com.github.joielechong:countrycodepicker:2.1.5'
        compile 'com.jaredrummler:material-spinner:1.2.4'
        compile 'hanks.xyz:htextview-library:0.1.5'
        compile 'com.firebaseui:firebase-ui-database:1.2.0'
        compile 'com.google.android.gms:play-services:11.8.0'
    }
    
    
    apply plugin: 'com.google.gms.google-services'
    


    Solution 1:

    None of the answers they gave you was exhaustive. The problem lies in the Multidex. You must add the library in the app gradle :

    implementation 'com.android.support:multidex:1.0.3'
    

    After, add in the defaultConfig of the app gradle :

    multiDexEnabled true
    

    Your Application must be of the Multidex type.. You must write it in the manifest :

    android:name=".MyApplication"
    

    "MyApplication" must be either the Multidex class, or it must extend it.

    Solution 2:

    Solution 3:

    modify your app's or module's build.gradle

    android {
        defaultConfig {
            ...
            minSdkVersion 21 <----- *here
            targetSdkVersion 26
            multiDexEnabled true <------ *here
        }
        ...
    }
    

    According to official documentation

    Multidex support for Android 5.0 and higher

    Android 5.0 (API level 21) and higher uses a runtime called ART which natively supports loading multiple DEX files from APK files. ART performs pre-compilation at app install time which scans for classesN.dex files and compiles them into a single .oat file for execution by the Android device. Therefore, if your minSdkVersion is 21 or higher, you do not need the multidex support library.

    For more information on the Android 5.0 runtime, read ART and Dalvik.

    https://developer.android.com/studio/build/multidex

  7. android - D8: Cannot fit requested classes in a single dex file
  8. Question:

    I am trying to add the below dependencies:

      firebase_auth: ^0.14.0+5
      google_sign_in: ^4.0.7
      cloud_firestore: ^0.12.9+5
      fluttertoast: ^3.1.3
      image_picker: ^0.6.1+8
      shared_preferences: ^0.5.3+4
      firebase_storage: ^3.0.6
      cached_network_image: 2.0.0-rc.1
      firebase_messaging: 6.0.13
      flutter_local_notifications: 1.4.0
      photo_view: ^0.5.0
    

    I found this error:

    D8: Cannot fit requested classes in a single dex file (# methods: 85948 > 65536)
    com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives:      
    The number of method references in a .dex file cannot exceed 64K.       
    Learn how to resolve this issue at https://developer.android.com/tools/building/multidex.html
            at com.android.builder.dexing.D8DexArchiveMerger.getExceptionToRethrow(D8DexArchiveMerger.java:131)
            at com.android.builder.dexing.D8DexArchiveMerger.mergeDexArchives(D8DexArchiveMerger.java:118)
            at com.android.build.gradle.internal.transforms.DexMergerTransformCallable.call(DexMergerTransformCallable.java:102)
            at com.android.build.gradle.internal.tasks.DexMergingTaskRunnable.run(DexMergingTask.kt:444)
            at com.android.build.gradle.internal.tasks.Workers$ActionFacade.run(Workers.kt:335)
            at org.gradle.workers.internal.AdapterWorkAction.execute(AdapterWorkAction.java:50)
            at org.gradle.workers.internal.DefaultWorkerServer.execute(DefaultWorkerServer.java:47)
            at org.gradle.workers.internal.NoIsolationWorkerFactory$1$1$1.create(NoIsolationWorkerFactory.java:65)
            at org.gradle.workers.internal.NoIsolationWorkerFactory$1$1$1.create(NoIsolationWorkerFactory.java:61)
            at org.gradle.internal.classloader.ClassLoaderUtils.executeInClassloader(ClassLoaderUtils.java:98)
            at org.gradle.workers.internal.NoIsolationWorkerFactory$1$1.execute(NoIsolationWorkerFactory.java:61)
            at org.gradle.workers.internal.AbstractWorker$1.call(AbstractWorker.java:44)
            at org.gradle.workers.internal.AbstractWorker$1.call(AbstractWorker.java:41)
            at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:416)
            at org.gradle.internal.operations.DefaultBuildOperationExecutor$CallableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:406)
            at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
            at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
            at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
            at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:102)
            at org.gradle.internal.operations.DelegatingBuildOperationExecutor.call(DelegatingBuildOperationExecutor.java:36)
            at org.gradle.workers.internal.AbstractWorker.executeWrappedInBuildOperation(AbstractWorker.java:41)
            at org.gradle.workers.internal.NoIsolationWorkerFactory$1.execute(NoIsolationWorkerFactory.java:56)
            at org.gradle.workers.internal.DefaultWorkerExecutor$3.call(DefaultWorkerExecutor.java:215)
            at org.gradle.workers.internal.DefaultWorkerExecutor$3.call(DefaultWorkerExecutor.java:210)
            at java.util.concurrent.FutureTask.run(FutureTask.java:266)
            at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.runExecution(DefaultConditionalExecutionQueue.java:215)
            at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.runBatch(DefaultConditionalExecutionQueue.java:164)
            at org.gradle.internal.work.DefaultConditionalExecutionQueue$ExecutionRunner.run(DefaultConditionalExecutionQueue.java:131)
            at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
            at java.util.concurrent.FutureTask.run(FutureTask.java:266)
            at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
            at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
            at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
            at java.lang.Thread.run(Thread.java:748)
    Caused by: com.android.tools.r8.CompilationFailedException: Compilation failed to complete
            at com.android.tools.r8.utils.t.a(:55)
            at com.android.tools.r8.D8.run(:11)
            at com.android.builder.dexing.D8DexArchiveMerger.mergeDexArchives(D8DexArchiveMerger.java:116)
            ... 34 more
    Caused by: com.android.tools.r8.utils.AbortException: Error: null, Cannot fit requested classes in a single dex file (# methods: 85948 > 65536)
            at com.android.tools.r8.utils.Reporter.a(:21)
            at com.android.tools.r8.utils.Reporter.a(:7)
            at com.android.tools.r8.dex.VirtualFile.a(:33)
            at com.android.tools.r8.dex.VirtualFile$h.a(:5)
            at com.android.tools.r8.dex.ApplicationWriter.a(:13)
            at com.android.tools.r8.dex.ApplicationWriter.write(:35)        
            at com.android.tools.r8.D8.d(:44)
            at com.android.tools.r8.D8.b(:1)
            at com.android.tools.r8.utils.t.a(:23)
            ... 36 more
    
    
    FAILURE: Build failed with an exception.
    
    * What went wrong:
    Execution failed for task ':app:mergeDexDebug'.
    > A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
       > com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives: 
         The number of method references in a .dex file cannot exceed 64K.
         Learn how to resolve this issue at https://developer.android.com/tools/building/multidex.html
    
    * Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
    
    * Get more help at https://help.gradle.org
    
    BUILD FAILED in 51s
    Running Gradle task 'assembleDebug'...
    Running Gradle task 'assembleDebug'... Done                        53.6s
    [!] The shrinker may have failed to optimize the Java bytecode.
        To disable the shrinker, pass the `--no-shrink` flag to this command.
        To learn more, see: https://developer.android.com/studio/build/shrink-code
    Exception: Gradle task assembleDebug failed with exit code 1
    

    and this is my full pubspec.yaml

    name: aradi_online_vtwo
    description: A new Flutter project.
    https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
    version: 1.0.0+1
    
    environment:
      sdk: ">=2.7.0 <3.0.0"
    
    dependencies:
      flutter:
        sdk: flutter
      provider: ^3.0.0
      intl: ^0.15.8
      flutter_speed_dial: ^1.2.1
      font_awesome_flutter: ^8.5.0
      smooth_star_rating: ^1.0.3
      firebase_auth: ^0.14.0+5
      google_sign_in: ^4.0.7
      cloud_firestore: ^0.12.9+5
      fluttertoast: ^3.1.3
      image_picker: ^0.6.1+8
      shared_preferences: ^0.5.3+4
      firebase_storage: ^3.0.6
      cached_network_image: 2.0.0-rc.1
      firebase_messaging: 6.0.13
      flutter_local_notifications: 1.4.0
      photo_view: ^0.5.0
    
      # The following adds the Cupertino Icons font to your application.
      # Use with the CupertinoIcons class for iOS style icons.
      cupertino_icons: ^0.1.2
    
    dev_dependencies:
      flutter_test:
        sdk: flutter
    
    
    # For information on the generic Dart part of this file, see the
    # following page: https://www.dartlang.org/tools/pub/pubspec
    
    # The following section is specific to Flutter.
    flutter:
    
      # The following line ensures that the Material Icons font is
      # included with your application, so that you can use the icons in
      # the material Icons class.
      uses-material-design: true
    
      # To add assets to your application, add an assets section, like this:
      assets:
        - assets/images/
        - assets/design_course/
        - assets/fitness_app/
        - assets/hotel/
    
      # An image asset can refer to one or more resolution-specific "variants", see
      # https://flutter.dev/assets-and-images/#resolution-aware.
    
      # For details regarding adding assets from package dependencies, see
      # https://flutter.dev/assets-and-images/#from-packages
    
      # To add custom fonts to your application, add a fonts section here,
      # in this "flutter" section. Each entry in this list should have a
      # "family" key with the font family name, and a "fonts" key with a
      # list giving the asset and other descriptors for the font. For
      # example:
      fonts:
        - family: WorkSans
          fonts:
            - asset: assets/fonts/WorkSans-Regular.ttf
            - asset: assets/fonts/WorkSans-Medium.ttf
              weight: 500
            - asset: assets/fonts/WorkSans-SemiBold.ttf
              weight: 600
            - asset: assets/fonts/WorkSans-Bold.ttf
              weight: 700
        - family: Roboto
          fonts:
            - asset: assets/fonts/Roboto-Bold.ttf
            - asset: assets/fonts/Roboto-Regular.ttf
            - asset: assets/fonts/Roboto-Medium.ttf
              weight: 400
      # For details regarding fonts from package dependencies,
      # see https://flutter.dev/custom-fonts/#from-packages
    

    So how can I solve this problem?


    Solution 1:

    Add multiDex to your app-level build.gradle file. Under defaultConfig add this line

    multiDexEnabled true
    

    Then in dependencies add multidex and check versions

    implementation 'androidx.multidex:multidex: 2.0.1'
    

    Solution 2:

    So basically this error happens when your app and the libraries it references exceed 65,536 methods,the build error just means your app has reached the limit of the Android build architecture, so to fix this go to android/app/build.gradle directory and add the multiDexEnabled true and implementation 'com.android.support:multidex:2.0.1' in thus manner

    defaultConfig {
            // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
            ........
            multiDexEnabled true
        }
    
    
    dependencies {
        ...........
        implementation 'com.android.support:multidex:2.0.1'
    }
    

    and of course restart your android-studio or the platform you're using.

    Solution 3:

    Upgrade min sdk to 21

    I had the same issue and Multi dex is not engouh to solve it I'm solve it with updgrading min sdk to 21

     defaultConfig {
        ...
        minSdkVersion 21
        targetSdkVersion 30
        multiDexEnabled
    }
    
    
    
     dependencies {
         ...
        implementation 'androidx.multidex:multidex:2.0.1'
    }
    

  9. android - NativeScript - Cannot fit requested classes in a single dex file
  10. Question:

    I am working on an app using the latest version of NativeScript with Angular. I have added most of the pro-ui plugins to my project and added the Firbase plugin.

    When I run “tns run android” I get the error:

    “D8: Cannot fit requested classes in a single dex file. Try supplying a main-dex list.”

    Also, it takes over 5 minutes to build. I have been doing some searching but I cannot find what is causing this problem. Does anyone know what is wrong?


    Solution 1:

    After much trial and error I have finally come to a solution. All other answers I've read have said that the multiDexEnabled property must be set to true in the android project's build.gradle file.

    I wasn't sure how to do this for NativeScript though since the platforms folder is not committed to version control and can be potentially overwritten.

    However, in your_project_root/app/App_resources/Android there are two files, settings.gradle and settings.json.

    settings.gradle is used to generate your projects's build.gradle file from the properties you set in settings.json.

    So, to the defaultConfig string template in settings.gradle I added:

    if(__multiDexEnabled__) {
        multiDexEnabled = __multiDexEnabled__
    }
    

    And to the JSON object defined in settings.json I added:

    "multiDexEnabled": true
    

    After that I deleted my project's platforms folder and ran:

    > tns platforms add android
    > tns run android
    

    And my app started up on my phone with no problems.

    Solution 2:

    Go to the path platforms/app/build.gradle (careful NOT /platform/build.gradle) and add the line multiDexEnabled true

    ...    
    defaultConfig {
                def manifest = new XmlSlurper().parse(file(android.sourceSets.main.manifest.srcFile))
                def minSdkVer = manifest."uses-sdk"."@android:minSdkVersion".text() ?: 17
                minSdkVersion minSdkVer
                targetSdkVersion computeTargetSdkVersion()
                ndk {
                    if (onlyX86) {
                        abiFilters 'x86'
                    } else {
                        abiFilters 'x86', 'x86_64', 'armeabi-v7a', 'arm64-v8a'
                    }
                }
                multiDexEnabled true
                dexOptions {
                    jumboMode = true
                }
            }
    ...
    

    Solution 3:

    I have solved this by Just adding multiDexEnabled true into your app.gradle under android->defaultConfig