Search code examples
javaandroidkotlinandroid-studiomobile

Android Stream.toList() does not work in the APK but works when the app is installed directly from the Android Studio


I am using this code

    var subList = mainList.stream()
                .flatMap(mainListItem ->
                        getSubItems(mainListItem.subItems).stream())
                .toList()

When I run this code after installing the app directly from Android Studio, it works fine, whereas when I run this after installing the APK, the toList() call fails with the error:

Caused by: java.lang.NoSuchMethodError: No interface method toList()Ljava/util/List; in class Lj$/util/stream/Stream; or its super classes (declaration of 'j$.util.stream.Stream' appears in /data/app/~~O_6UL0ys4sQP9iQ4qmUjjQ==/com.package.name-PBAatiCc4N4NNAIsUiGUfg==/base.apk!classes19.dex)

I have desugaring enabled in my code and I am using the proper configuration for it:

    compileOptions {
        coreLibraryDesugaringEnabled true

        sourceCompatibility JavaVersion.VERSION_11
        targetCompatibility JavaVersion.VERSION_11
    }

    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_11.toString()
    }

The desugaring library version used is 1.1.5.

coreLibraryDesugaring "com.android.tools:desugar_jdk_libs:1.1.5"

I have tried disabling minifyEnabled and shrinkResources but to no avail.


Solution

  • After lingering for some time, I realised that the issue was indeed with the Stream API I used. It turned out that Stream.toList() was added in Java 16. The Gradle JDK version I am using is Java 17 hence the code compiled. Android Studio suggested toList() in red but the code was compiling and running without issues unless I installed the app via APK.

    I replaced all the Stream.toList() calls with Stream.collect(Collectors.toList()) and it worked without issues.

    After searching through the developer docs and the desugaring release notes, it turned out that Stream.toList() is not supported for the library version I am using as it is not mentioned anywhere in the APIs list as supported.