When I add ONE SHARE SDK as dependency I get the following error message:
Error:Execution failed for task ':app:transformClassesWithDexBuilderForDebug'.
com.android.build.api.transform.TransformException: org.gradle.tooling.BuildException:
com.android.dx.cf.iface.ParseException: class name (com/sina/weibo/sdk/component/view/CommentComponentView$RequestParam)
does not match path (weiboSDKCore_3.1.2/com/sina/weibo/sdk/component/view/CommentComponentView$RequestParam.class)
What could be the cause of this error?
Adding the following code to build.gradle app module solved my problem
android{
defaultConfig {
// Enabling multidex support.
multiDexEnabled true
}
dexOptions {
javaMaxHeapSize "4g"
}
}
dependencies {
//...
compile 'com.android.support:multidex:1.0.0'
}
Source Code
It's probably a rare scenario, but I had it. Previously, an android-support-v4.jar file was manually added to my project. This was done before the use of the gradle. Remove the file and the build was successful.
Sounds like the error is recognizing a class cast issue. It expects CommentComponentView$RequestParam.class
but it getting something else. Could be different version or duplicate named class where it is trying to figure out which one to use and it is using the wrong one.
For example if I have a class called
public class MyClass {
}
and the SDK has a class called
public class MyClass {
}
then in the usage it could be confusing the two. Check your import statements to make sure you are using the correct path and version of the parameter that it is expecting as maybe it is a duplicate class that is confusing it by accessing the wrong version of that class.
This may not be your issue, but worth checking out. Goodluck.
Related
How to solve this error I'm getting in Android Studio:
Error: Cannot fit requested classes in a single dex file (# methods: 67593 > 65536)
cant build my project now
Do this 4 step
1: Add this library in dependencies of the app build.gradle :
implementation 'com.android.support:multidex:1.0.3'
2: Add in the defaultConfig of the app build.gradle :
defaultConfig {
//other configs
multiDexEnabled true //add this line
}
3: Create new Java class like this :
public class ApplicationClass extends MultiDexApplication {
#Override
public void onCreate() {
super.onCreate();
}
}
4: Add this to your manifest (in application tag):
<application
android:name=".ApplicationClass"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name">
Same situation happened in my Visual Studio 2019 Xamarin project, and the way to solve this problem is just like what mentioned in the link:
Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536
multiDexEnabled true
By checking the Enable multiDex checkbox in the option page of the ***.Droid project solves the problem.
Before you take any decision, as said in Google documentation :
Before configuring your app to enable use of 64K or more method
references, you should take steps to reduce the total number of
references called by your app code, including methods defined by your
app code or included libraries.
So try to remove useless importation in your app gradle and do a nice clean project or do multidex
Source : https://developer.android.com/studio/build/multidex
Created a new Dynamic Feature Module: dynamic, build fails with the below exception:
Execution failed for task ':dynamic:processDebugManifest'.
Expected configuration ':dynamic:debugCompileClasspath' to contain exactly one file, however, it contains no files.
Tried adding baseFeature true to the app gradle, and getting error:
Could not find method baseFeature() for arguments [true] on object of type com.android.build.gradle.internal.dsl.BaseAppModuleExtension.
I solved this, you need to have all flavors of the base module in your dynamic feature module also
I had the same error message but the problem was with the common KTS script I was using across the feature modules:
This was wrong:
private fun Project.configureDependencies() {
dependencies.project(":app")
}
This was right:
private fun Project.configureDependencies() = dependencies{
add("implementation", project(":app"))
}
Hope this helps some poor soul
I want to use Android Data Binding and has configured according to the official document.
the error message is :
error: cannot find symbol import net.juude.droidviews.BR;
the top level build.gradle file is:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath "com.android.tools.build:gradle:1.3.0-beta2"
classpath 'me.tatarka:gradle-retrolambda:3.0.1'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4'
classpath "com.android.databinding:dataBinder:1.0-rc0"
}
}
allprojects {
repositories {
jcenter()
mavenCentral()
}
}
and the build.gradle file in app module is
apply plugin: 'com.android.application'
apply plugin: 'me.tatarka.retrolambda'
apply plugin: 'com.neenbedankt.android-apt'
apply plugin: 'com.android.databinding'
android {
compileSdkVersion 22
buildToolsVersion "22.0.1"
lintOptions {
abortOnError false
}
defaultConfig {
applicationId "net.juude.droidviews"
minSdkVersion 15
targetSdkVersion 22
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
retrolambda {
println("JAVA_HOME: " + System.getenv("JAVA_HOME"))
println("JAVA7_HOME: " + System.getenv("JAVA7_HOME"))
println("JAVA8_HOME: " + System.getenv("JAVA8_HOME"))
javaVersion JavaVersion.VERSION_1_7
}
}
dependencies {
compile project(':ptr-lib-debug')
compile project(':library')
compile 'com.android.support:support-v4:22.1.0'
compile 'com.mcxiaoke.volley:library:1.0.+'
compile files('libs/droidmocks.jar')
compile 'com.android.support:support-annotations:22.1.1'
compile 'com.facebook.fresco:fresco:0.5.0'
compile 'com.android.support:recyclerview-v7:22.1.1'
compile 'io.reactivex:rxandroid:0.24.0'
compile 'io.reactivex:rxjava:1.0.6'
compile 'com.google.dagger:dagger:2.0'
apt 'com.google.dagger:dagger-compiler:2.0'
}
the layout file is
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable name="user" type=" net.juude.droidviews.databinding.User" />
</data>
<LinearLayout
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/user_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{user.mName}"/>
<TextView
android:id="#+id/user_sex"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{user.sex}"/>
</LinearLayout>
</layout>
the fragment is
package net.juude.droidviews.databinding;
import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import net.juude.droidviews.BR;
import net.juude.droidviews.R;
/**
* Created by juude on 15-6-9.
*/
public class DataBindingFragment extends Fragment{
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewDataBinding dataBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_data_binding, container, false);
//dataBinding.setVariable(BR.)
User user = new User();
user.setSex("男");
user.setName("Juude");
dataBinding.setVariable(BR.user, user);
return dataBinding.getRoot();
}
}
since I did not get syntax error in Android Studio, I can assume that the Android Studio can recognize the BR class;
But when I compile the project, It tells me that
error:cannot find symbol class BR.
so I want to know what should I do to make it generate the right BR.java file?
In case someone still has this problem. I solved this by invalidating the cache in Android Studio. And I'm using Android Studio 2 with API 23
File > Invalidate Caches/Restart
It is a problem caused by android-apt plugin. It ignores the provided dependency that data binding plugin adds.
https://bitbucket.org/hvisser/android-apt/issue/38/android-apt-breaks-brand-new-data-binding#comment-18504545
You can work around it by adding:
apt 'com.android.databinding:compiler:1.0-rc0 to your gradle file.
If you are using Kotlin, try applying the following plugin to your app build.gradle file:
apply plugin: 'kotlin-kapt'
Clean your project and build it again. This solved the issue for me.
I find the cause of the problem in my case. I find in the import statements of my Data Object class contains:
import static android.databinding.tool.util.GenerationalClassUtil.ExtensionFilter.BR;
The problem gets solved after I removed that. Android Studio somehow resolved BR class wrongly for me.
The Bindable annotation generates an entry in the BR class file during compilation. The BR class file will be generated in the module package.
#Bindable
public String getFirstName() {
return this.firstName;
}
I ran into this issue too. The problem was that I changed the class name and didn't update the values in the XML file. This includes the variable names and where they are accessed in the xml file.
For my case the issue was caused by
"error: variable MyVariable was already defined in class MyModel"
The annoying thing was Android Studio gradle build did not display this error at the bottom. I had to comment each databinding error > Rebuild Project until I reach the error. Lesson learnt was to scan through each error from bottom to top and notice anything you may have changed recently.
I too got the same error message, but my root cause was different from what has been shared here.
In my case the issue was that after I resolved a merge conflict, I had by mistake left an extra #Override annotation on a method. Thus the JVM preprocessor failed and then also the data binding classes were not generated.
The irritating part for me was that I was unable to see any error message related to this, or it was hard to spot among all the other compiler errors. And Android Studio does not show the extra annotation as an error either. So in case someone else struggles with the same error, check that you don't haven an error in some annotation that prevents the APT preprocessor from kicking in.
You need to add this to your gradle.properties file
android.databinding.enableV2=true
From developer.android.com
you might get multiple errors reporting that the binding classes aren't found. The new data binding compiler prevents these errors by generating the binding classes before the managed compiler builds your app.
Just restarting Android Studio, without invalidating cache, did the trick for me (I'm using version 2.2.3).
I had this plus 29 other errors suddenly crop up from one moment to the next. I tried clean, rebuild, invalidate caches / restart and no luck. In the end I removed changes I had made and redid them one by one. Found that I had #Injected a service in the wrong class. Once I removed that all 30 errors were gone. The errors gave no clue to what I had done wrong.
If you use Android Studio 2.3 release and your project configuration is as follow:
Gradle version: 3.3
Android plugin version:2.3.0
Compile sdk Version:23+
build tools Version:25+
All need to do is add
dataBinding{enabled=true}
to build.gradle, then sync gradle file.
For me it helped to run ./gradlew clean build in the project folder. It showed an error which android studio didn't.
Generally BR class Generate automatically when you Rebuild your project and I have resolved the problem using this technique Still have issue you can try another solution.
You need to double-check the following steps:
GradleFile:
dataBinding {enabled = true}
Your class Model.
import androidx.databinding.BaseObservable
import androidx.databinding.Bindable
import androidx.databinding.library.baseAdapters.BR
class User2(
private var firstName: String,
private var lastName: String
) : BaseObservable() {
fun setFirstName(firstName: String) {
this.firstName = firstName
notifyPropertyChanged(BR.firstName)
}
#Bindable
fun getFirstName(): String {
return this.firstName
}
}
If you are using Dagger 2, the problem may be caused by dagger's components. Although two libraries are not related, in my case, fixing errors in Dagger reported in the compiler makes the BR class properly appear again.
BR gets generated during compilation, Build -> Rebuild project should do the trick. But for me it failed with error:
e:/home/xx/File.kt: (24, 46): Expecting an element because on that line I had an incompleted BR.. Just commenting or adding anything after . and rebuilding solved it.
Just follow the steps below,
1.Extend your class with BaseObservable class
2.Add #Bindable annotation to each getter methods.
3.Rebuild the project.
Now you'll be able to access BR
In my case, I tried just running the project and it fixed the issue.
Add dependency
implementation "androidx.lifecycle:lifecycle-extensions:2.1.0"
Then sync project. Even if not works, invalidate cache and restart then clean & rebuild project.
In my case i haven't provided #PrimaryKey annotation on one of the entity and it was really difficult to find this error as in logs there are no clue to find it. so be sure to give your Entity a primary key, else this error occurs.
Check your room database related file, because of that class gradle build get failed, and will not get idea actually. issue is in room classes.
what ever androidx.databinding.library.baseAdapters.BR error your getting those file is not generating because of room database class have some syntax error
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
I'm converting my app to use gradle, and I'm trying to use the buildTypes. I have a Constants class which I wish to modify for my release build. So I have a file at src/main/java/my/package/name/Constants.java and at src/release/java/my/package/name/Constants.java.
When I try to build this, gradle tells me the build failed on the Constants file in my release buildtype, with the error that it's a duplicate class.
I also tried adding a different sourceSet for this in my build.gradle like this:
sourceSets {
main {
java.srcDirs = ['src/main/java'];
//...
}
release {
java.srcDirs = ['src/release/java'];
}
}
But this still gives me the same error. So I'm wondering, what am I doing wrong here?
You can not have a class in main and release. You need to split it into something like debug and release.
gradle will merge the source sets for each buildType with main.
This is the reason, why the class gets duplicated in your release build.
So the rule is: put a class into main, or in every buildType but not both.
The answer from "fix" helped me on the way, but I got an error from the main Gradle, saying a constant was missing (in my class Config). This since I had my class only in paid and free version and not in main. Could not find the Config class.
Im not sure if this is a bug in Studio... I finally solved it with the following:
buildTypes {
release {
...
buildConfig "public static final boolean XYZ = false;"
}
}
And the instead of using my Config.XYZ class constant I used buildConfig.XYZ