Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android app throws NoClassDefFoundError after setting Gradle SourceSets

I am trying to understand how to set sourcesets in build.gradle.kts file. For that i have a test project. The project structure is as follows-
app
-src
--main
---java
----com.example.myapplication
-----MainActivity.kt
--sample2
---java
----com.example.myapp.legacy
-----LegacyFile.java

LegacyFile.java

package com.example.myapp.legacy;

public class LegacyFile {

}

Here, i wan to create instance of LegacyFile inside MainActivity.kt file -

    override fun onCreate(savedInstanceState: Bundle?) {
....
        val legacyFile = LegacyFile()
} 

So, i added the following lines to app/build.gradle.kts file -

android {
.....
    sourceSets.getByName("main").apply {
        kotlin.setSrcDirs(listOf("src/sample2/java"))
    } 
}

Now, the project compiles successfully. But, when i run the app it throws an exception -

FATAL EXCEPTION: main Process: com.example.myapplication, PID: 2436 java.lang.NoClassDefFoundError: Failed resolution of: Lcom/example/myapp/legacy/LegacyFile; at com.example.myapplication.MainActivity.onCreate(MainActivity.kt:25) ..... Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.myapp.legacy.LegacyFile" on path: DexPathList[[dex file "/data/data/com.example.myapplication/code_cache/.overlay/base.apk/classes5.dex", zip file "/data/app/~~5E7UPyWAZdlsGbzLHVOIJw==/com.example.myapplication-kmtHz5UXr_gzaXYqPtpKyA==/base.apk"],nativeLibraryDirectories=[/data/app/~~5E7UPyWAZdlsGbzLHVOIJw==/com.example.myapplication-kmtHz5UXr_gzaXYqPtpKyA==/lib/x86_64, /system/lib64, /system_ext/lib64]]

When i inspect the apk file, i can see LegacyFile - Android Studio apk viewer

Can someone please explain what i am doing wrong here?

Thanks!

like image 272
user1122549 Avatar asked Jan 21 '26 22:01

user1122549


1 Answers

Update to this:

android {
.....
    sourceSets.getByName("main") {
        java.srcDir("src/sample2/java")
    } 
}

or

android {
.....
    sourceSets.getByName("main") {
        java.srcDirs += ['src/sample2/java']
    } 
}

FYI: kotlin.srcDirs didn't work because you are trying to source .java files instead of .kt files.

like image 163
Anish B. Avatar answered Jan 24 '26 10:01

Anish B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!