Google Play game services - Android samples errors - android

Based on Android docs (https://developers.google.com/games/services/android/quickstart#before_you_begin) for learning how to configure Google Play game APIs onto a sample app such as TypeANumber, I was wondering why I get the following resource errors from the BaseGameUtils library after importing the project, BasicSamples, from their GitHub's (https://github.com/playgameservices/android-basic-samples) source files:
... Based on the directory in the left panel, did I import it properly? All I did was import it straight from the directory: android-basic-samples/BasicSamples/build.gradle as stated in Step 1 of the link.
Here's my (untouched) Gradle file for the library, BaseGameUtils:
apply plugin: 'com.android.library'
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.3.1'
}
}
dependencies {
// Set defaults so that BaseGameUtils can be used outside of BasicSamples
if (!project.hasProperty('appcompat_library_version')) {
ext.appcompat_library_version = '20.0.+'
}
if (!project.hasProperty('support_library_version')) {
ext.support_library_version = '20.0.+'
}
if (!project.hasProperty('gms_library_version')) {
ext.gms_library_version = '8.1.0'
}
compile "com.android.support:appcompat-v7:${appcompat_library_version}"
compile "com.android.support:support-v4:${support_library_version}"
compile "com.google.android.gms:play-services-games:${gms_library_version}"
compile "com.google.android.gms:play-services-plus:${gms_library_version}"
}
android {
// Set defaults so that BaseGameUtils can be used outside of BasicSamples
if (!project.hasProperty('android_compile_version')) {
ext.android_compile_version = 23
}
if (!project.hasProperty('android_version')) {
ext.android_version = '23'
}
compileSdkVersion android_compile_version
buildToolsVersion android_version
}
... Did anyone else experience this issue before?
EDIT AS OF 4/7, 3:37PM:
So I ended up importing the project again, but within the AndroidStudioProjects directory this time (does that really make a difference?) and I actually ended up making some progress since then. However, for part 3 under step 1 within the docs:
... I ended up changing not only the package name in TypeANumber's manifest file, but also the package directory along with the classes in it as follows:
... So my question now is, am I on the right track so far in terms of the navigation directory panel at the left? :)

Yes. The package attribute in the manifest should always match the directories. Plain and simple. That's why changing it would require you to do a complete refactor. Just keep on going with the tutorial accordingly and I think you'll be good.

Related

Kotlin Native compile jar and framework

I'm building a multiplatform library for Android and iOS. My gradle file looks like this:
plugins {
id 'org.jetbrains.kotlin.multiplatform' version '1.4.0'
}
repositories {
mavenCentral()
}
group 'com.example'
version '0.0.1'
apply plugin: 'maven-publish'
kotlin {
jvm()
// This is for iPhone simulator
// Switch here to iosArm64 (or iosArm32) to build library for iPhone device
ios {
binaries {
framework()
}
}
sourceSets {
commonMain {
dependencies {
implementation kotlin('stdlib-common')
implementation("com.ionspin.kotlin:bignum:0.2.2")
}
}
commonTest {
dependencies {
implementation kotlin('test-common')
implementation kotlin('test-annotations-common')
}
}
jvmMain {
dependencies {
implementation("com.ionspin.kotlin:bignum:0.2.2")
}
}
jvmTest {
dependencies {
implementation kotlin('test')
implementation kotlin('test-junit')
}
}
iosMain {
}
iosTest {
}
}
}
configurations {
compileClasspath
}
Im using a third party library and I'm using it like this:
fun test(value: String): Int {
return BigDecimal.parseString(value).toBigInteger().intValue()
}
The problem is when I build the .jar the bignum library isn't included, and when I use the lib in an Android project I get an exception ClassNotFoundException: Didn't find class "com.ionspin.kotlin.bignum.decimal.BigDecimal".
Is there a way to include third party libs in the .jar for Android and .framework for iOS?
JVM
So, the only way I've found to generate a Fat JAR that works like you expect is by adding two custom gradle tasks in project:build.gradle.kts of your KMP library after appling the java plugin.
plugins {
[...]
id("java")
}
[...]
kotlin {
jvm {
[...]
compilations {
val main = getByName("main")
tasks {
register<Copy>("unzip") {
group = "library"
val targetDir = File(buildDir, "3rd-libs")
project.delete(files(targetDir))
main.compileDependencyFiles.forEach {
println(it)
if (it.path.contains("com.")) {
from(zipTree(it))
into(targetDir)
}
}
}
register<Jar>("fatJar") {
group = "library"
manifest {
attributes["Implementation-Title"] = "Fat Jar"
attributes["Implementation-Version"] = archiveVersion
}
archiveBaseName.set("${project.name}-fat")
val thirdLibsDir = File(buildDir, "3rd-libs")
from(main.output.classesDirs, thirdLibsDir)
with(jar.get() as CopySpec)
}
}
tasks.getByName("fatJar").dependsOn("unzip")
}
}
[...]
}
You then must launch the fatJar gradle task that generate a .jar file with the 3rd libraries classes extracted from they corresponding jar archives.
You can customize the two custom gradle scripts even more in order to better fit your needs (here I only included com. package name starting deps).
Then in your Android app app:build.gradle file you can use it as you did or simply
implementation files('libs/KMLibraryTest001-fat-1.0-SNAPSHOT.jar')
iOS
As you ask also for the iOS part in your title (even if it's a second citizen in the main topic of your question) you need only to use api instead of implementation for your 3rd party library along with the export option of the framework.
ios() {
binaries {
framework() {
transitiveExport = true // all libraries
//export(project(":LibA")) // this library project in a trainsitive way
//export("your 3rd party lib") // this 3rd party lib in a transitive way
}
}
}
And you can find a full reference here.
If you see the Krypto library, it has
androidMain
jsMain
jvmMain
mingwX64Main
nativPosixMain
Which means 5 kind of binaries are generated to support 5 platforms
Convincingly, this explains that each platform expects its own binary
for example,
windows -- DLL file
linux -- so file
java -- JAR file
mac -- dylib file
A JAR gets loaded into JVM, but IOS does not use JVM
Separate your Utility functions which has a common logic and write gradle to target multiple platforms
If you want to start with pure multiplatform, you can try this Official Example
Or create a sub gradle module and create a library project which is common to IOS as well as Android
The possible targets are properly documented here
I have created a application which publishes the binary to local repository and re-uses in the MainActivity -- you can get the code here
modify the local.properties for android SDK location and use
gradlew assemble
to build the APK and test it yourself
open the mylib\build.gradle.kts folder and you can see the targets jvm and iosX64 , jvm is used for android
If I'm correct using api instead of implementation should fix your problem, though I didn't try it out yet on the Native part
See Api and implementation separation

kotlinx.android.synthetic unused android studio issue

I am working one project using kotlin + Rxjava + MVVM. During development facing issue of importing view ids in Fragment or viewholder.
import kotlinx.android.synthetic.main.layout.* unused with kotlin.
Normaly view id should used from kotlin synthetic layout imports but it directly import it from R.id that should not happen.
Kotlin plugin version : org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.40
My gradle file :
apply plugin: 'com.android.feature'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'idea'
apply plugin: 'kotlin-kapt'
android {
compileSdkVersion 27
baseFeature true
defaultConfig {
minSdkVersion 23
targetSdkVersion 27
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
lintOptions {
abortOnError false
}
}
dependencies {
api "com.android.support:design:$rootProject.support_library_version"
api "com.android.support:appcompat-v7:$rootProject.support_library_version"
api "com.android.support:recyclerview-v7:$rootProject.support_library_version"
api "com.android.support:support-dynamic-animation:$rootProject.support_library_version"
api "com.android.support:cardview-v7:$rootProject.support_library_version"
api "com.android.support:customtabs:$rootProject.support_library_version"
api "com.android.support.constraint:constraint-layout:1.1.0-beta5"
api 'android.arch.lifecycle:extensions:1.1.0'
api 'androidx.core:core-ktx:0.2'
api "com.google.dagger:dagger:$rootProject.dagger_version"
kapt "com.google.dagger:dagger-compiler:$rootProject.dagger_version"
api "android.arch.persistence.room:runtime:$rootProject.room_version"
kapt "android.arch.persistence.room:compiler:$rootProject.room_version"
testImplementation "android.arch.persistence.room:testing:$rootProject.room_version"
api "android.arch.persistence.room:rxjava2:$rootProject.room_version"
androidTestImplementation "android.arch.core:core-testing:$rootProject.room_version"
testImplementation "android.arch.core:core-testing:$rootProject.room_version"
api "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
api "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"
api 'com.jakewharton.timber:timber:4.5.1'
api "com.android.support:multidex:1.0.3"
api "com.github.bumptech.glide:glide:$rootProject.glide_version"
api "jp.wasabeef:glide-transformations:$rootProject.glide_transformation_version"
api 'com.github.bumptech.glide:okhttp3-integration:1.5.0#aar'
api "io.reactivex.rxjava2:rxandroid:$rootProject.rxAndroid_version"
api "io.reactivex.rxjava2:rxjava:$rootProject.rxJava_version"
api "com.google.code.gson:gson:$rootProject.gson_version"
api("com.squareup.retrofit2:retrofit:$rootProject.retrofit_version") {
// exclude Retrofit’s OkHttp peer-dependency module and define your own module import
exclude module: 'okhttp'
}
api "com.squareup.okhttp3:okhttp:$rootProject.okhttp_version"
api "com.squareup.okhttp3:logging-interceptor:$rootProject.okhttp_version"
api "com.squareup.retrofit2:adapter-rxjava2:$rootProject.retrofit_version"
api "com.squareup.retrofit2:converter-gson:$rootProject.retrofit_version"
api 'com.jakewharton.threetenabp:threetenabp:1.0.5'
api "com.google.firebase:firebase-invites:$rootProject.play_services_version"
api "com.google.firebase:firebase-core:$rootProject.play_services_version"
api "com.google.firebase:firebase-config:$rootProject.play_services_version"
api "com.google.firebase:firebase-perf:$rootProject.play_services_version"
api "com.google.firebase:firebase-auth:$rootProject.play_services_version"
api "com.google.firebase:firebase-firestore:$rootProject.play_services_version"
api("com.firebaseui:firebase-ui-auth:$rootProject.firebase_ui_version") {
// exclude Retrofit’s OkHttp peer-dependency module and define your own module import
exclude module: 'play-services-auth'
exclude module: 'firebase-auth'
}
// Required only if Facebook login support is required
api('com.facebook.android:facebook-android-sdk:4.31.0')
api "com.google.android.gms:play-services-auth:$rootProject.play_services_version"
// Required only if Twitter login support is required
api("com.twitter.sdk.android:twitter-core:3.0.0#aar") { transitive = true }
api 'com.jakewharton.rxbinding2:rxbinding-kotlin:2.0.0'
api 'com.jakewharton.rxbinding2:rxbinding-support-v4-kotlin:2.0.0'
api 'com.jakewharton.rxbinding2:rxbinding-appcompat-v7-kotlin:2.0.0'
api 'com.jakewharton.rxbinding2:rxbinding-design-kotlin:2.0.0'
api('com.crashlytics.sdk.android:crashlytics:2.9.1#aar') {
transitive = true
}
}
I have also tried clean build and Rebuild project.
Any idea how can i resolve this issue ?
I have tried several approaches including the solutions reported in this thread. I also found out that a lot of folks are facing this annoying problem as you can see here
Nevertheless, the most closest solution to this problem which has worked for me so far is removing apply plugin: kotlin-android-extensions from gradle, Sync gradle plugin and then add it again.
I'm using Android Studio 3.1.3 and I encountered the same issue. I managed to solve this by moving all my codes from java/ to kotlin/ directory inside main/.
app/
|-- src/
| |-- main/
| | |-- java/
| | | |-- com.example.android.app
| | |-- kotlin/ <-- (use this)
| | | |-- com.example.android.app
Then, add the kotlin/ as part of the source sets:
app/build.gradle
android {
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
}
Sometimes, it still requires to sync and rebuild the project to properly import the kotlinx.android....
Reference: Add kotlin code
I have the same problem and I am trying to solve it for too many days...
One trick you can do is to Exclude from Import and Completion <package-name>.R.id.* for project scope.
Go to Settings/Editor/Auto Import to add it.
It improves our issue and if you do this and clean the project, it will work but it does not resolve the issue completely. Many times the imports reappear as unused imports and there is to clean the project over and over :-(.
EDITED
Also, another improvement I have achieved is working with includes on XML. For example, if I am going to use "the same" button in several screens, I make a specific layout for this button and I re-use it on several activities / fragments. You can set the id within this specific layout and synthetic will auto-import it without generating conflicts, due to you have the content view reference declared before.
I show you a simple example:
activity_main.xml
<!-- ... -->
<include layout="#layout/btn_foo"/>
<!-- ... -->
btn_foo.xml
<?xml version="1.0" encoding="utf-8"?>
<Button
android:id="#+id/btnFoo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android"/>
MainActivity.kt
// ...
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.btn_foo.*
// ...
setContentView(R.layout.activity_main)
// ...
btnFoo.setOnClickListener { }
I have to admit that in the other cases I have returned to the typical Hungarian convention whatWhereDescription(Size) to set the ids due to is too much annoying to deal with imports among activities / fragments / view all the time.
I've solved similar issues for ViewHolder implementations:
We have to inherit our ViewHolder class implementation from LayoutContainer. LayoutContainer is an interface available in kotlinx.android.extensions package.
You will have some code similar with this:
class TaskVH(override val containerView: View, val itemListener: TasksFragment.TaskItemListener) : RecyclerView.ViewHolder(containerView), LayoutContainer {
fun bindItem(task: Task) {
item_title.text = ""
item_complete.isChecked = task.isCompleted
itemView.setBackgroundResource(rowViewBackground)
itemView.setOnClickListener { itemListener.onTaskClick(task) }
}
}
I don't know if this tripped anyone else up, but I was having problems because I didn't realize the synthetic objects are only available if you're inside an Activity, Dialog, or Fragment. If you're in some other class (like using Conductor's Controller) you're out of luck.
Cross-posting my bug report with workaround from here: https://issuetracker.google.com/issues/145888144
Original bug was closed as "fixed" by google, but it is definitely not fixed: https://issuetracker.google.com/issues/78547457
SUMMARY:
For some modules in a multi-module project, the IDE does not properly recognize imports for "synthetic" symbols that abstract view ids, a feature provided by the plugin 'kotlin-android-extensions'. This results in class files using these symbols appearing full of errors, as the imports are "unresolved", the symbols are then unknown, and of course anything using these symbols fail because the types are unknown.This is solely an IDE problem though; everything compiles normally and works as expected.
ROOT CAUSE
The kotlin-language facet is not being applied to the errant modules.
BACKGROUND
Facets in IntelliJ IDEA projects are configurable on a module-by-module basis in Project settings. In Android Studio, this part of the Project settings UI is missing (or suppressed.) Presumably, Android Studio is attempting to apply the correct facets based on the gradle plugins applied to each module. This process is /sometimes/ FAILING for this particular case; I have not been able to determine what triggers the success/failure of the process.
TEMPORARY WORKAROUND
This workaround works consistently, and has since 3.5.2 when I discovered it:
Open the ".iml" file for the module you are trying to "fix" in Android Studio editor. (In AS > 4, the iml file is in .idea/modules, earlier than that it was in top-level of your module.) Find the <component name="FacetManager"> block, and notice that there is no facet called "kotlin-language" there. Paste the contents of the text block below so it appears within the <component name="FacetManager"> block. Save the file.
Re-import gradle.
This is a clumsy workaround, and has to be applied on a module-by-module basis. What's more, it may be required to sometimes re-apply the workaround after making changes to the build.gradle file for an affected module. The hope is that Google (or JetBrains, if it turns out it is their problem) will fix this problem properly.
Given that kotlin-android-extensions has fallen out of favor, I don't expect this bug will ever be fixed.
Text to use for the fix
<facet type="kotlin-language" name="Kotlin">
<configuration version="3" platform="JVM 1.8" allPlatforms="JVM [1.8]" useProjectSettings="false">
<compilerSettings />
<compilerArguments>
<option name="jvmTarget" value="1.8" />
<option name="pluginOptions">
<array>
<option value="plugin:org.jetbrains.kotlin.android:enabled=true" />
<option value="plugin:org.jetbrains.kotlin.android:defaultCacheImplementation=hashMap" />
</array>
</option>
</compilerArguments>
</configuration>
</facet>
There is an existing issue (which is assigned) on Google tracker regarding synthetic imports.
https://issuetracker.google.com/issues/78547457
For Conductor:
Create this base class.
import android.os.Bundle
import android.view.View
import com.bluelinelabs.conductor.Controller
import com.bluelinelabs.conductor.RestoreViewOnCreateController
abstract class BaseController(
bundle: Bundle? = null
) : RestoreViewOnCreateController(bundle){
init {
addLifecycleListener(object : LifecycleListener() {
override fun postCreateView(controller: Controller, view: View) {
onViewCreated(view)
}
})
}
open fun onViewCreated(view: View) { }
}
Then in your controller:
import kotlinx.android.synthetic.main.controller_example.view.*
class ProfileController : BaseController() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle?): View {
return inflater.inflate(R.layout.controller_example, container, false)
}
override fun onViewCreated(view: View) {
view.txtName.text = "Example"
}
}
I try every other solution bu no one worked for me. At the and I cloned project again and now it's working. I love android studio
Add id kotlin-android-extensions in your build.gradle file in the plugins block.
Google removed this feature by default

Build with moverio BT-2000 library

I'm trying to develop apps for EPSON Moverio BT-2000.
I'm new to android studio and I don't understand why I can't use some methods from a library which I have imported (correctly, I supposed).
So, I have add my lib in a folder name libs, right click on it, add as Library.
I checked in builds.gradle
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile files('libs/H725Ctrl.jar') // this lib
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:21.0.3'
}
Moreover, I can use some elements (Methods, String definitions etc..) but some not. I don't understand why and how it's possible.
If it's necessary I can publish my source code.
Have you some ideas.?
Thanks.
Franck
NB: the lib I use is depreciated by android
NB2: Exemple
Camera.Parameters params = l_pCamera.getParameters();
// I can do this and getParameters() works
List<String> Supported = params.getSupportedEpsonCameraModes();
//I can't invoke getSupportedEpsonCameraModes() or methods are in the same file
I contacted EPSON and they said it's a common problem.
So they send me a pdf which indicate how solve the problem..
It's strange..
NB the content of the PDF: sorry for the presentation but it will be helpful for someone..
1/2
Remark for using Android Studio
In case of using BT-2000 SDK with Android Studio, there may happen to have a failure during a build process. It may cause the conflict of the name between standard SDK and Epson expanded SDK. It is happened especially with “android.hardware.Camera” class.
It may resolve a failure with following action.
1. Sore H725Ctrl.jar at designated folder which is created by user like C:\Users\<user name\AndroidStudioProjects\<application name>\app\libs
2. Set change of gradle by selecting “Sync Project with Gradle Files” button which is located upper of Android Studio screen.
3. Open “build.gradle” for specified project with specified application name by selecting left side button on Android Studio screen. Then edit with following contents.
allprojects { repositories { jcenter() } gradle.projectsEvaluated { tasks.withType(JavaCompile) { options.compilerArgs.add('-Xbootclasspath/p:C:/Users/<user name>/AndroidStudioProjects/<application name>/app/libs/H725Ctrl.jar') } } }
4. Execute “Clean Project” then “Make Project” in Android Studio Build menu.
5. If error occurs in Make project process, end Android Studio and restart it.
2/2
6. There may still remain several name conflicts with Android standard API like “getSupportedEpsonCameraModes()”. Ignore and “run application” to set it into target BT-2000.
[ Caution ]
It works temporally with following action;
Open
C:\Users\<user name>\AndroidStudioProjects\<application name>\app\app.iml
Move line of
<orderEntry type="library" exported="" name="H725Ctrl" level="project" />
to upper line of
<orderEntry type="jdk" jdkName="Android API 23 Platform" jdkType="Android SDK" />
This will help H725Ctrl.jar to be higher priority, however performing rebuild function will affect to reset name conflict issue.
Object which is performed build function already works well.
It's weird. Epson tries to override some Android specific classes in their jar:
android.hardware.Camera
android.hardware.Camera.Parameters
These classes are part of the Android SDK (http://developer.android.com/reference/android/hardware/Camera.html). I do not know Epson would like to achieve, if they bundle the classes with their SDK. Maybe you could change the packagename in the H725Ctrl.jar to something like
com.epson.hardware
with JarJar (https://github.com/shevek/jarjar)?
Add the following code to your build.gradle file. The problem could be that the Moverio Camera class uses the same namespace as the Android sdk and there is an ordering issue
allprojects {
repositories {
jcenter()
}
gradle.projectsEvaluated {
tasks.withType(JavaCompile) {
options.compilerArgs.add('-Xbootclasspath/p:C:/Source/EPSONProBT-2000ServiceMaintenance/app/libs/H725Ctrl.jar')
}
}
}

Separating integration tests from unit tests in Android Studio

I'm trying to separate out integration tests in Android Studio 0.9.
I have added the following to the build file:
sourceSets {
integrationTest {
java.srcDir file('src/integrationTest/java')
}
}
task integrationTest(type: Test) {
testClassesDir = sourceSets.integrationTest.output.classesDir
classpath = sourceSets.integrationTest.runtimeClasspath
}
I've run into a couple of issues:
The task will run but it doesn't have the rest of the project files available so I get errors about missing classes. There are some Java specific solutions I've found such as:
http://selimober.com/blog/2014/01/24/separate-unit-and-integration-tests-using-gradle/
https://blog.safaribooksonline.com/2013/08/22/gradle-test-organization/
But I haven't been able to figure out how to get this to work with Android Studio. Various combinations of main and main.output and playing around with dependencies don't seem to work, I get errors like:
Error:(33, 0) Could not find property 'main' on SourceSet container..
Which makes sense as the android plugin defines its own source sets, but these don't work either.
The IDE doesn't recognise the directory as a test source directory. For testing purposes I changed the source set name to androidTest and it correctly gets the green folder icon and the tests are run along with the existing unit tests that are already defined in androidTest.
#sm4's answer works indeed for a Java module (with apply plugin: 'java'), but unfortunately not for Android application (apply plugin: 'com.android.application') nor Android library modules (apply plugin: com.android.library).
But I have found a workaround:
Create the folders for your integration tests:
src/integrationTest/java
src/integrationTest/res
Add the sourceSets for your new folders:
sourceSets {
integrationTest {
java {
srcDir file('src/integrationTest/java')
}
res {
srcDir file('src/integrationTest/res')
}
}
}
In a pure Java module the java folder would now turn green and the res folder icon would change. In an Android application/library module it does not.
Now create a product flavor identically named as the folder configured in the sourceSet, and it works!
productFlavors {
integrationTest {
}
}
And to put a cherry on top:
configurations {
integrationTestCompile.extendsFrom testCompile
}
I've done exactly this kind of separation in Gradle, but for a pure Java project, not Android. You are not specifying the classpath in source sets, which I think is the issue. Here's the relevant part of the build.gradle:
sourceSets {
integration {
java {
compileClasspath += main.output + test.output
runtimeClasspath += main.output + test.output
srcDir file('src/integration/java')
}
resources {
srcDir 'src/integration/resources'
}
}
}
configurations {
integrationCompile.extendsFrom testCompile
integrationRuntime.extendsFrom testRuntime
}
task integrationTest(group: "verification", type: Test) {
testClassesDir = sourceSets.integration.output.classesDir
classpath = sourceSets.integration.runtimeClasspath
}
integrationTest.dependsOn testClasses
IntelliJ idea picks up the folders under src/integration if they have the standard names (java, resources).

DexIndexOverflowException with build tool 21.0.0 [duplicate]

I have seen various versions of the dex erros before, but this one is new. clean/restart etc won't help. Library projects seems intact and dependency seems to be linked correctly.
Unable to execute dex: method ID not in [0, 0xffff]: 65536
Conversion to Dalvik format failed: Unable to execute dex: method ID not in [0, 0xffff]: 65536
or
Cannot merge new index 65950 into a non-jumbo instruction
or
java.util.concurrent.ExecutionException: com.android.dex.DexIndexOverflowException: method ID not in [0, 0xffff]: 65536
tl;dr: Official solution from Google is finally here!
http://developer.android.com/tools/building/multidex.html
Only one small tip, you will likely need to do this to prevent out of memory when doing dex-ing.
dexOptions {
javaMaxHeapSize "4g"
}
There's also a jumbo mode that can fix this in a less reliable way:
dexOptions {
jumboMode true
}
Update: If your app is fat and you have too many methods inside your main app, you may need to re-org your app as per
http://blog.osom.info/2014/12/too-many-methods-in-main-dex.html
Update 3 (11/3/2014)
Google finally released official description.
Update 2 (10/31/2014)
Gradle plugin v0.14.0 for Android adds support for multi-dex. To enable, you just have to declare it in build.gradle:
android {
defaultConfig {
...
multiDexEnabled true
}
}
If your application supports Android prior to 5.0 (that is, if your minSdkVersion is 20 or below) you also have to dynamically patch the application ClassLoader, so it will be able to load classes from secondary dexes. Fortunately, there's a library that does that for you. Add it to your app's dependencies:
dependencies {
...
compile 'com.android.support:multidex:1.0.0'
}
You need to call the ClassLoader patch code as soon as possible. MultiDexApplication class's documentation suggests three ways to do that (pick one of them, one that's most convenient for you):
1 - Declare MultiDexApplication class as the application in your AndroidManifest.xml:
<?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>
2 - Have your Application class extend MultiDexApplication class:
public class MyApplication extends MultiDexApplication { .. }
3 - Call MultiDex#install from your Application#attachBaseContext method:
public class MyApplication {
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
....
}
....
}
Update 1 (10/17/2014):
As anticipated, multidex support is shipped in revision 21 of Android Support Library. You can find the android-support-multidex.jar in /sdk/extras/android/support/multidex/library/libs folder.
Multi-dex support solves this problem. dx 1.8 already allows generating several dex files.
Android L will support multi-dex natively, and next revision of support library is going to cover older releases back to API 4.
It was stated in this Android Developers Backstage podcast episode by Anwar Ghuloum. I've posted a transcript (and general multi-dex explanation) of the relevant part.
As already stated, you have too many methods (more than 65k) in your project and libs.
Prevent the Problem: Reduce the number of methods with Play Services 6.5+ and support-v4 24.2+
Since often the Google Play services is one of the main suspects in "wasting" methods with its 20k+ methods. Google Play services version 6.5 or later, it is possible for you to include Google Play services in your application using a number of smaller client libraries. For example, if you only need GCM and maps you can choose to use these dependencies only:
dependencies {
compile 'com.google.android.gms:play-services-base:6.5.+'
compile 'com.google.android.gms:play-services-maps:6.5.+'
}
The full list of sub libraries and it's responsibilities can be found in the official google doc.
Update: Since Support Library v4 v24.2.0 it was split up into the following modules:
support-compat, support-core-utils, support-core-ui, support-media-compat and support-fragment
dependencies {
compile 'com.android.support:support-fragment:24.2.+'
}
Do note however, if you use support-fragment, it will have dependencies to all the other modules (ie. if you use android.support.v4.app.Fragment there is no benefit)
See here the official release notes for support-v4 lib
Enable MultiDexing
Since Lollipop (aka build tools 21+) it is very easy to handle. The approach is to work around the 65k methods per dex file problem to create multiple dex files for your app. Add the following to your gradle build file (this is taken from the official google doc on applications with more than 65k methods):
android {
compileSdkVersion 21
buildToolsVersion "21.1.0"
defaultConfig {
...
// Enabling multidex support.
multiDexEnabled true
}
...
}
dependencies {
compile 'com.android.support:multidex:1.0.1'
}
The second step is to either prepare your Application class or if you don't extend Application use the MultiDexApplication in your Android Manifest:
Either add this to your Application.java
#Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
or use the provided application from the mutlidex lib
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.myapplication">
<application
...
android:name="android.support.multidex.MultiDexApplication">
...
</application>
</manifest>
Prevent OutOfMemory with MultiDex
As further tip, if you run into OutOfMemory exceptions during the build phase you could enlarge the heap with
android {
...
dexOptions {
javaMaxHeapSize "4g"
}
}
which would set the heap to 4 gigabytes.
See this question for more detail on the dex heap memory issue.
Analyze the source of the Problem
To analyze the source of the methods the gradle plugin https://github.com/KeepSafe/dexcount-gradle-plugin can help in combination with the dependency tree provided by gradle with e.g.
.\gradlew app:dependencies
See this answer and question for more information on method count in android
Your project is too large. You have too many methods. There can only be 65536 methods per application. see here https://code.google.com/p/android/issues/detail?id=7147#c6
The below code helps, if you use Gradle. Allows you to easily remove unneeded Google services (presuming you're using them) to get back below the 65k threshold. All credit to this post: https://gist.github.com/dmarcato/d7c91b94214acd936e42
Edit 2014-10-22: There's been a lot of interesting discussion on the gist referenced above. TLDR? look at this one: https://gist.github.com/Takhion/10a37046b9e6d259bb31
Paste this code at the bottom of your build.gradle file and adjust the list of google services you do not need:
def toCamelCase(String string) {
String result = ""
string.findAll("[^\\W]+") { String word ->
result += word.capitalize()
}
return result
}
afterEvaluate { project ->
Configuration runtimeConfiguration = project.configurations.getByName('compile')
ResolutionResult resolution = runtimeConfiguration.incoming.resolutionResult
// Forces resolve of configuration
ModuleVersionIdentifier module = resolution.getAllComponents().find { it.moduleVersion.name.equals("play-services") }.moduleVersion
String prepareTaskName = "prepare${toCamelCase("${module.group} ${module.name} ${module.version}")}Library"
File playServiceRootFolder = project.tasks.find { it.name.equals(prepareTaskName) }.explodedDir
Task stripPlayServices = project.tasks.create(name: 'stripPlayServices', group: "Strip") {
inputs.files new File(playServiceRootFolder, "classes.jar")
outputs.dir playServiceRootFolder
description 'Strip useless packages from Google Play Services library to avoid reaching dex limit'
doLast {
copy {
from(file(new File(playServiceRootFolder, "classes.jar")))
into(file(playServiceRootFolder))
rename { fileName ->
fileName = "classes_orig.jar"
}
}
tasks.create(name: "stripPlayServices" + module.version, type: Jar) {
destinationDir = playServiceRootFolder
archiveName = "classes.jar"
from(zipTree(new File(playServiceRootFolder, "classes_orig.jar"))) {
exclude "com/google/ads/**"
exclude "com/google/android/gms/analytics/**"
exclude "com/google/android/gms/games/**"
exclude "com/google/android/gms/plus/**"
exclude "com/google/android/gms/drive/**"
exclude "com/google/android/gms/ads/**"
}
}.execute()
delete file(new File(playServiceRootFolder, "classes_orig.jar"))
}
}
project.tasks.findAll { it.name.startsWith('prepare') && it.name.endsWith('Dependencies') }.each { Task task ->
task.dependsOn stripPlayServices
}
}
I've shared a sample project which solve this problem using custom_rules.xml build script and a few lines of code.
I used it on my own project and it is runs flawless on 1M+ devices (from android-8 to the latest android-19). Hope it helps.
https://github.com/mmin18/Dex65536
Faced the same problem and solved it by editing my build.gradle file on the dependencies section, removing:
compile 'com.google.android.gms:play-services:7.8.0'
And replacing it with:
compile 'com.google.android.gms:play-services-location:7.8.0'
compile 'com.google.android.gms:play-services-analytics:7.8.0'
Try adding below code in build.gradle, it worked for me -
compileSdkVersion 23
buildToolsVersion '23.0.1'
defaultConfig {
multiDexEnabled true
}
The perfect solution for this would be to work with Proguard. as aleb mentioned in the comment.
It will decrease the size of the dex file by half.
You can analyse problem (dex file references) using Android Studio:
Build -> Analyse APK ..
On the result panel click on classes.dex file
And you'll see:
gradle + proguard solution:
afterEvaluate {
tasks.each {
if (it.name.startsWith('proguard')) {
it.getInJarFilters().each { filter ->
if (filter && filter['filter']) {
filter['filter'] = filter['filter'] +
',!.readme' +
',!META-INF/LICENSE' +
',!META-INF/LICENSE.txt' +
',!META-INF/NOTICE' +
',!META-INF/NOTICE.txt' +
',!com/google/android/gms/ads/**' +
',!com/google/android/gms/cast/**' +
',!com/google/android/gms/games/**' +
',!com/google/android/gms/drive/**' +
',!com/google/android/gms/wallet/**' +
',!com/google/android/gms/wearable/**' +
',!com/google/android/gms/plus/**' +
',!com/google/android/gms/topmanager/**'
}
}
}
}
}
Remove some jar file from Libs folder and copy to some other folder, And Go to _Project Properties > Select Java Build Path, Select Libraries, Select Add External Jar, Select the Removed jar to your project, Click save, this will be added under Referenced Library instead of Libs folder. Now clean and Run your project. You dont need to add Any code for MultDex. Its simply worked for me.
I was facing the same issue today what worked for is below down
For ANDROID STUDIO... Enable Instant Run
In File->Preferences->Build, Execution, Deployment->Instant Run-> Check Enable Instant run for hot swap...
Hope it helps

Categories

Resources