Reputation: 9102
I have Android gradle project which consists of main module and a pure java library. The java library has a dependency on a jar file (Gson is shown here for demo purposes only):
The project compiles fine but when I try to run it it fails with NoClassDefFoundError
:
java.lang.NoClassDefFoundError: com.google.gson.Gson
at com.example.JavaLibClass.javaMethod(JavaLibClass.java:7)
at com.denisk.deptest.MainActivity.onCreate(MainActivity.java:15)
at android.app.Activity.performCreate(Activity.java:5135)
If I replace jar
dependency with regular Maven dependency, it works.
If I move jar
dependency from javalib
to app
and introduce dependency Gson
dependency in the activity, it works.
app/build.gradle dependencies:
dependencies {
compile project(':javalib')
}
javalib/build.gradle:
apply plugin: 'java'
dependencies {
compile files('libs/gson-2.2.4.jar')
}
MainActivity's onCreate
(inside app
):
@Override
protected void onCreate(Bundle savedInstanceState) {
JavaLibClass javaLibClass = new JavaLibClass();
javaLibClass.javaMethod();
}
JavaLibClass (inside javalib
):
public class JavaLibClass {
public void javaMethod() {
Gson gson = new Gson();
}
}
Github repository with the demo project:
https://github.com/denisk20/android-gradle-dependency-test
Am I doing something wrong or is it a bug?
Edit 1: It doesn't matter whether I build with Android Studio or with pure Gradle.
Edit 2:
I have have tried it with android gradle plugin 1.4.0-beta4
from AOSP - same error.
Upvotes: 4
Views: 1511
Reputation: 8111
The class which is failing to load probably has a missing dependency of its own. Annoyingly, the VM in Android 5.1 does not tell you what that dependency is. I found that when I ran my app on an older Android 2.3 device with the Dalvik VM, the missing dependency was identified in a log message.
Upvotes: 1
Reputation: 3055
Okay, Its not a bug actually, instead you need to import the jar file as a dependency in your project. I believe that you just put that Jar file in the lib folder of your project but did not import as dependency in your project. That is why the maven dependency is working fine since it automatically import it. So, go to File>Project Structure, Select your project under module section and on Dependency tab, add your jar file as File dependency by browsing to your lib folder. Now, rebuild your project, It should work fine.
Upvotes: 0