Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Library project com.android.dex.DexException: Multiple dex files define Lcom/google/gson/JsonSerializer

I am writing a library project in Android Studio. My gradle file includes gson volley play-services etc...
When embedding my library in a project I get:

com.android.dex.DexException: Multiple dex files define Lcom/google/gson/JsonSerializer;

Could someone explain how gradle works when creating library projects?
What should I explain the developer who integrates my SDK, how does exclude module work, and why it is not working in the app that is including my aar?

like image 871
Noam Segev Avatar asked Aug 10 '16 13:08

Noam Segev


2 Answers

There two cases that need to consider on

  • First, consider to remove Gson if you have declared it in app/build.gradle

    dependencies { compile 'com.google.code.gson:gson:2.4' }

  • Second, if you have not declare it in your app/build.gradle You may need to investigate which libraries that has duplicate declare Gson dependency. Then you can exclude the Gson from that library. You may want to check this Excluding transitive dependencies

Here, I will provide an example of exclude appcompat-v7 from a library

Run this command to see the dependencies chart tree

./gradlew app:dependencies

It will display the dependencies tree like the sample below

|    \--- com.mikepenz:materialdrawer:4.6.3
|         +--- com.android.support:appcompat-v7:23.1.1 (*)
|         +--- com.android.support:recyclerview-v7:23.1.1 (*)
|         +--- com.mikepenz:materialize:0.5.1
|         |    \--- com.android.support:appcompat-v7:23.1.1 (*)
|         +--- com.mikepenz:iconics-core:2.5.3
|         |    \--- com.android.support:appcompat-v7:23.1.1 (*)
|         \--- com.android.support:support-annotations:23.1.1

After you found library declared duplicate dependency. You can start exclude it.

dependencies {
    compile("com.mikepenz:materialdrawer:4.6.3") {
        exclude module: 'appcompat-v7'
    }
}
like image 142
THANN Phearum Avatar answered Oct 23 '22 16:10

THANN Phearum


If remove GSON is not an option for you, try enablin multidex support into your build.gradle file:

android {
   ...
   ...
         defaultConfig {
             ...
             ...
             // Enabling multidex support.
             multiDexEnabled true
         }
}
like image 44
Jorgesys Avatar answered Oct 23 '22 15:10

Jorgesys