Android compiles source code into dex files which is executed by Dalvik. While integrating a new library project into the maincode base, I got the above build time error.
While researching the problem, here are some things I came across:
1. Each Android dex file can contain a max of 65, 536 method references (i.e.) a method reference count is incremented by 1, whenever there is a unique reference to a method from an Android project.
2. If a project grows big enough to contain more than ~65K method references, the library files can be built as separate dexes.
3. Dex files can be dynamically loaded in the main activity’s onCreate method. See example.
4. Even if 2 Android library projects referenced the same Android project, the method reference count is counted twice – provided the 2 Android library projects have different manifest package names (i.e.) package name defined in the manifest node in AndroidManifest.xml file.
To provide an example of #4 above, see portions of the dex build error stack trace below that caught my attention. It indicates the method reference count for these library projects – all hovering close to the number 6852. The only common library/jar reference in all these library projects referenced the android framework library itself.
Error:Android Dex: [MainProject] 6852 android.support.v7.appcompat
Error:Android Dex: [MainProject] 6964 com.handmark.pulltorefresh.library
Error:Android Dex: [MainProject] 6852 com.company.lib.ui
and so on…..
Given the above, some potential work-arounds emerged:
1. Do away with the need for library projects. Package everything into one monolithic structure.
2. Split the project files into multiple dex files.
#1 goes against fundamental software principles of software development – code needs to be developed as re-usable libraries.
#2 is a good long-term solution but is more complex.
The solution: A reasonable medium term solution emerged after understanding #4 more closely. The significance of Package name within the manifest tag in the AndroidManifest.xml file is that it is used as a fully qualifying name to identify Android resources. It does not have anything to do with the package name for the java classes themselves. So I tweaked 1 manifest package name (new library project) to be the same as the top level project (MainProject) manifest package name. And the dex build error was gone!
The following command returns the count of methods in a dex file: