Telegram

ANDROID STUDIO’S GRADLE ISSUE

Resolving Android Studio’s Gradle Issue: A Comprehensive Guide for Windows Environments

We understand the immense frustration that accompanies Gradle build failures in Android Studio, particularly when the issue is intermittent or persists after standard troubleshooting steps. The specific error you are encountering, Execution failed for task ':app:compileDebugJavaWithJavac', which points to a failure in transforming core-for-system-modules.jar using jlink.exe, indicates a complex interaction between the JDK, the Android SDK, and the Gradle build system. This is a nuanced problem that often resides deeper than simple cache corruption or path misconfiguration. Our objective is to provide a definitive, step-by-step guide to diagnose and permanently resolve this issue. We will dissect the error, explore the underlying causes, and implement robust solutions that ensure your development environment remains stable across multiple builds and project restarts.

Understanding the Core Error: :app:compileDebugJavaWithJavac and androidJdkImage

To effectively solve this problem, we must first understand what is happening under the hood when Gradle executes the build process. The error message provides critical clues about the specific stage of the build pipeline where the failure occurs.

The Role of Java Compilation in Gradle

The task :app:compileDebugJavaWithJavac is responsible for compiling the Java source code (and potentially Kotlin source code that is compiled to JVM bytecode) in your application module. This task uses the javac compiler, which is part of the Java Development Kit (JDK). However, modern Android builds, especially those utilizing Android Gradle Plugin (AGP) 8.0 and higher, have introduced a new mechanism for managing the Java runtime environment required for compilation. This is where the androidJdkImage configuration comes into play.

The Significance of androidJdkImage and System Modules

The androidJdkImage is a dependency configuration that defines the specific JDK image required to compile your Android application. This is not just a pointer to a JDK folder; it is a modular runtime image generated using a tool called jlink. The jlink tool is part of the Java Platform Module System (JPMS) introduced in Java 9. It assembles a custom Java runtime image containing only the modules necessary for a specific application.

In the context of Android development, the build system uses jlink to create a minimal, optimized JDK image tailored for compiling against the Android API. The file core-for-system-modules.jar is a critical component of the Android SDK (specifically for android-36, corresponding to Android 14), which contains the system modules required for compilation. The error indicates that the build system is failing to transform this JAR file into a format compatible with the jlink process to generate the required JDK image.

Dissecting the jlink.exe Failure

The specific command that fails is: C:\AndroidStudio\jbr\bin\jlink.exe --module-path ... --add-modules java.base --output ... --disable-plugin system-modules

This command attempts to generate a custom JDK image in a temporary directory within the Gradle cache. The failure points to one of several potential issues:

  1. File Corruption: The input files (JARs) or the jlink executable itself may be corrupted.
  2. Path Length Limits: On Windows, the generated file paths within the .gradle cache directory can exceed the maximum path length limit (260 characters), causing jlink to fail.
  3. JDK Incompatibility: The JDK used to run jlink (in this case, the JetBrains Runtime inside C:\AndroidStudio\jbr) may be incompatible with the Android SDK tools or the Gradle version.
  4. Permissions and Antivirus Interference: The jlink process may be blocked from writing to the cache directory by Windows permissions or by antivirus software that locks files during their creation.

We will address each of these possibilities systematically.

Preliminary Diagnostics: Verifying Your Environment

Before applying aggressive fixes, we must ensure the foundational components of your development environment are correctly configured. Inconsistencies here are a common source of intermittent build failures.

JDK Version and Location

The Android Gradle Plugin requires a specific JDK version. While Android Studio ships with its own embedded JDK (the JetBrains Runtime or JBR), manual Gradle builds or specific configurations might inadvertently point to a different JDK installed on the system (like Oracle JDK or OpenJDK). This mismatch can cause jlink to fail, as the tool’s behavior varies between JDK versions.

We recommend the following checks:

  1. Open Android Studio and navigate to Settings > Build, Execution, Deployment > Build Tools > Gradle.
  2. Verify the Gradle JDK dropdown is set to the embedded JDK provided by Android Studio (usually labeled as “jbr-17” or similar). Do not use a standalone JDK unless you have a specific reason to do so and know it is compatible with your AGP version.
  3. In your system’s environment variables, check JAVA_HOME. While Android Studio manages its own environment, terminal commands or CI scripts often rely on JAVA_HOME. Ensure it points to the same JDK used by Android Studio to avoid conflicts.

Android SDK Path and Permissions

The error explicitly references the Android SDK location: C:\Users\ELITEX21012G2\AppData\Local\Android\Sdk. We must confirm this path is accessible and not corrupted.

  1. Verify SDK Location: In Android Studio, go to Settings > Appearance & Behavior > System Settings > Android SDK. Note the Android SDK path.
  2. Check Folder Permissions: Navigate to this path in Windows Explorer. Right-click the Sdk folder, select Properties > Security, and ensure that your user account has “Full control” permissions. If not, modify the permissions to allow write access.
  3. Validate SDK Components: Open the SDK Manager within Android Studio. Ensure that Android SDK Platform 36 and Android SDK Build-Tools are fully installed and do not show any errors. If there are any pending updates or installation issues, resolve them immediately. A partial or corrupted installation of android-36 is a direct cause of the core-for-system-modules.jar error.

Windows Long Path Limitation

Windows has a default maximum path length of 260 characters. Gradle’s caching mechanism creates deeply nested directories, often resulting in file paths that exceed this limit, especially for users with long usernames (like ELITEX21012G2).

We can verify and resolve this by:

  1. Enabling the “Enable Long Paths” feature in Windows 10/11 via the Group Policy Editor or Registry.
  2. Alternatively, move the Android SDK and Gradle cache to shorter root paths (e.g., C:\Android\Sdk and C:\gradle-cache). This is a highly effective, albeit more disruptive, solution.

Comprehensive Solutions for Gradle Build Failures

We will now proceed with a tiered approach to fixing the issue, starting with standard cleanups and moving to more advanced configurations.

Solution 1: Deep Cache and Build Artifact Cleanup

Simply deleting the .gradle folder is often insufficient because it does not always clear all temporary transforms or locked files. We need a more thorough approach.

  1. Invalidate Caches and Restart:

    • In Android Studio, go to File > Invalidate Caches / Restart….
    • Select “Invalidate and Restart”. This clears all local history, system caches, and restarts the IDE. This is the first line of defense against transient IDE issues.
  2. Manual Deletion of Caches and Build Directories:

    • Close Android Studio completely.
    • Navigate to your project directory and delete the .gradle and .idea folders. Also, delete the build folder inside your project root and inside the app module.
    • Navigate to the global Gradle cache, typically located at C:\Users\[YourUser]\.gradle\caches. Delete the entire contents of this folder. This will force Gradle to re-download all dependencies and regenerate necessary transforms. Note: This will increase the time of your next build significantly.
    • Navigate to the local Android SDK build-tools directory (e.g., C:\Users\[YourUser]\AppData\Local\Android\Sdk\build-tools\[version]) and delete any temporary files if present.
  3. Clean Project and Rebuild:

    • After restarting Android Studio and reopening your project, run a clean build from the terminal or the IDE: gradlew clean. Then attempt to build the project again.

If the standard cleanup fails, the issue is likely rooted in the jlink execution itself. The error Failed to transform core-for-system-modules.jar suggests that the Gradle transform task is encountering an error while invoking the system’s JDK or the embedded JDK.

Forcing a Specific JDK for Toolchain

The Android Gradle Plugin uses a concept called “JVM Toolchain” to compile Java/Kotlin code. Sometimes, the auto-detection fails. We can explicitly define the toolchain in your build.gradle file.

Open your module-level build.gradle (usually app/build.gradle) and add the following inside the android block:

android {
    // ... other configurations

    // Explicitly define the JDK toolchain for compilation
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_17
        targetCompatibility JavaVersion.VERSION_17
    }
    
    kotlinOptions {
        jvmTarget = '17'
    }
}

Furthermore, ensure your gradle.properties file contains settings that align with the embedded JDK. Add or modify these lines:

org.gradle.java.home=C\:\\AndroidStudio\\jbr
android.useAndroidX=true
android.enableJetifier=true

Note: Ensure the path to the JDK is correct. Escape backslashes properly in gradle.properties.

Disabling the Modules Plugin (Workaround)

The error message includes --disable-plugin system-modules. This indicates that the system-modules plugin is part of the problem. While the build system usually handles this automatically, you can try to influence this behavior by adjusting how Gradle handles the JDK.

In your gradle.properties, try adding:

org.gradle.jvmargs=-Xmx4096m -Dkotlin.daemon.jvm.options="-Xmx4096m" --add-opens=java.base/java.lang=ALL-UNNAMED --add-opens=java.base/java.lang.invoke=ALL-UNNAMED --add-opens=java.base/java.io=ALL-UNNAMED --add-opens=java.base/java.nio=ALL-UNNAMED

These arguments open specific Java modules to reflection, which can sometimes resolve jlink generation errors caused by module encapsulation issues.

Solution 3: Manual Gradle Installation and Configuration

You mentioned trying a manual Gradle setup but faced issues with Android Studio accepting the path. This is often due to a mismatch between the Gradle version specified in gradle-wrapper.properties and the version installed manually.

  1. Download Gradle: Download the specific version of Gradle required by your project (check gradle/wrapper/gradle-wrapper.properties for the distributionUrl). For example, if it uses 8.13, download the “bin” distribution of Gradle 8.13 from the official website.
  2. Extract and Configure: Extract the archive to a short path, such as C:\Gradle\gradle-8.13.
  3. Set Environment Variables:
    • Create a new system variable named GRADLE_HOME pointing to C:\Gradle\gradle-8.13.
    • Append %GRADLE_HOME%\bin to the Path variable.
  4. Configure Android Studio:
    • Go to Settings > Build, Execution, Deployment > Build Tools > Gradle.
    • Under Gradle Projects, select “Use Gradle from ‘GRADLE_HOME’” or “Use Gradle from specified location” and point it to C:\Gradle\gradle-8.13.
    • Crucially: Ensure the “Gradle JVM” dropdown still points to the Android Studio embedded JDK (jbr-17). Do not change this.
  5. Apply and Sync: Click Apply and OK, then sync your project. This manual separation often stabilizes the build environment by bypassing the IDE’s internal Gradle wrapper mechanism, which may have been corrupted.

Solution 4: Antivirus and Windows Defender Exclusions

Antivirus software frequently interferes with the build process. The jlink.exe process creates many temporary files rapidly, and heuristic scanning can flag this behavior as suspicious, locking files and causing the process to crash.

We strongly advise adding the following directories to your Antivirus/Windows Defender exclusion list:

To do this in Windows Security:

  1. Open Windows Security > Virus & threat protection > Manage settings > Exclusions.
  2. Add each folder listed above as an exclusion. This prevents the antivirus from scanning files during the build process, significantly improving build speed and stability.

Solution 5: Addressing the VS Code and Flutter Context

You mentioned that the issue persists in VS Code with Flutter. This confirms that the problem is not specific to Android Studio but is a system-level issue with the Android SDK and Gradle configuration.

When using Flutter, the android folder inside your Flutter project is still an Android project managed by Gradle. Therefore, all the solutions above apply directly.

  1. Check Flutter Doctor: Run flutter doctor -v in your terminal. Ensure it detects the correct Android SDK and JDK.
  2. Clean Flutter Build: Run flutter clean to delete build artifacts, then flutter pub get.
  3. Delete the .gradle folder: Just as with the Android Studio project, manually delete the .gradle folder located inside your Flutter project’s android directory.
  4. Recreate the android folder: If the issue persists, the android module might be corrupted. As a last resort, you can delete the android folder (backup any custom configurations first) and regenerate it using flutter create . --platforms=android. Warning: This will remove custom native code.

Preventative Measures and Best Practices

Once your build is stable, implementing these practices will prevent the recurrence of jlink and Gradle issues.

Manage Gradle Version and Android Gradle Plugin (AGP) Compatibility

Incompatible versions of Gradle and AGP are a primary source of build failures. Always refer to the official Android Gradle Plugin release notes which table the compatible versions.

Example configuration in build.gradle:

plugins {
    id 'com.android.application' version '8.2.0' apply false // Or latest stable
    id 'com.android.library' version '8.2.0' apply false
    id 'org.jetbrains.kotlin.android' version '1.9.10' apply false
}

In gradle-wrapper.properties:

distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-bin.zip

Matching these versions exactly as per the official documentation minimizes compatibility risks.

Use Offline Mode for Gradle (Advanced)

If you are in an environment with unstable internet, Gradle’s attempts to download dependencies can timeout or result in corrupted downloads, which can trigger transformation errors. While not a direct fix for jlink, it stabilizes the environment. You can enable “Offline work” in Settings > Build, Execution, Deployment > Gradle, but only after all dependencies have been successfully downloaded and cached.

Regular Maintenance of the .gradle Folder

Over time, the .gradle folder accumulates stale artifacts. Periodically (e.g., once a month), perform a deep clean by deleting the .gradle/caches directory. Alternatively, use the Gradle built-in command to clean up old versions: gradlew --stop (stops the daemon) gradlew clean (cleans project build) Then manually delete the cache folders if build issues arise.

Conclusion

The Execution failed for task ':app:compileDebugJavaWithJavac' error, specifically related to the androidJdkImage transformation and jlink.exe, is a complex issue rooted in the interaction between the Java runtime, the Android SDK, and the Windows file system. We have established that this is not a simple configuration error but often requires a multi-pronged approach.

By verifying your JDK and SDK configurations, aggressively cleaning your build environment, manually configuring Gradle to avoid wrapper corruption, and mitigating external interference from antivirus software, we can resolve this issue. The most effective solution often combines a manual Gradle installation with a deep cleanup of the .gradle and .android directories. Applying these measures ensures that your Android Studio, Flutter, and VS Code environments remain stable, allowing you to focus on development rather than troubleshooting build tools. Remember, consistency in your development environment configuration is the key to avoiding these frustrating interruptions.

Explore More
Redirecting in 20 seconds...