Showing posts with label Gradle. Show all posts
Showing posts with label Gradle. Show all posts

Monday, November 27, 2023

How I fixed the Android Studio current target and jvm target compatibility error

I encountered the following compilation error in Android Studio of one of my Android project about current target JVM compatibility (or incompatibility), as shown in the screenshot message listing below:

 

Execution failed for task ':app:compileDebugKotlin'.
> 'compileDebugJavaWithJavac' task (current target is 1.8) and 'compileDebugKotlin' task (current target is 17) jvm target compatibility should be set to the same Java version.
  Consider using JVM toolchain: https://kotl.in/gradle/jvm/toolchain

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

I managed to fix the problem by ensuring the source and target are compatible, i.e. having the same Java version.

To fix the issue:

  1. In Android Studio, select File | Project Structure.

    The Project Structure dialog box appears.


  2. Click Gradle Settings.

    The Gradle dialog box appears.


  3. In the Use Gradle from combo box, choose 'gradle-wrapper.properties' file.

  4. In the Gradle JDK combo box, choose jbr-17 JetBrains Runtime version 17.

  5. Click OK to close all dialog boxes.

  6. In Android Studio, open the app's build.gradle file in the editor.


  7. Within the android construct, add in the compileOptions as shown in the listing below.

android {
    compileSdk 33

// ...etc...

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_17
        targetCompatibility JavaVersion.VERSION_17
    }
}

From this point on, compiling the app should not throw upany  JVM target compatibility errors.

Monday, November 15, 2021

Android Studio: Fixing the warning "flatDir should be avoided"

After upgrading my gradle plugin to version 7, I encountered this warning message "Using flatDir should be avoided because it doesn't support any meta-data format".

As shown in the screenshot below, I have the word flatDir under the repositories keyword inside my Android app's build.gradle file.

 

This flatDir is used to point to the location of my local Android library file(s), named inside the build.gradle's dependencies section - shown below.

To fix the warning, all I needed to do was to do the following:

  1. Remove the flatDir part from the build.gradle file's repositories section. 
  2. Inside the build.gradle's dependencies section, replace the local Android library name implementation with the following relative path to the local library file name with extension :

    implementation files ( 'libs/my-local-library.aar')

    An example is shown below.

 

Monday, August 17, 2020

Android Studio: Fix for Default Activity not found warning

Recently after upgrading Android Studio to version 4.x, I found some of my old Android projects showing a warning message: "Warning: Default Activity not found" when I tried to run the project in the emulator; and Android Studio would not be able to launch the app. 

I tried the following:

  • Build | Clean project in Android Studio
    • Invalidate Caches / Restart in Android Studio
  • Verified AndroidManifest.xml is declaring the main activity correctly
  • Deleted the Android Studio caches - .idea/, .gradle/, *.iml

None worked.

When I tried to edit the run configuration, no matter what launch options I chose, the warning message still persisted, as shown in the screenshot below and I could not run the application. 

Finally, systematically I discovered the problem to be related to the Google Play Services AdMob dependency. The app's build.gradle snippet below shows the dependency.

dependencies { 
 
 implementation 'com.google.android.gms:play-services-ads:19.3.0'

}

Note: When using the newer Google Play Services Ads, the minimum SDK must now be set to at least 16. 

The screenshot below shows the Android Studio project when using 14 as the minimum SDK level. Notice the large red cross.

The screenshot shows the state of the Android Studio project after changing the minimum SDK level to 16 and selecting File | Sync Project with Gradle Files. Notice the large red cross is no longer displayed. Android Studio should be able to launch the app from this point on.
 

Monday, November 11, 2019

Android Studio: Automatically replace the Google Maps V2 API Key for debug and release mode

The Android Google Maps API requires a separate debug and release keys in the Android Studio project's AndroidManifest.xml file, as shown in the listing below.

<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="your_google_maps_v2_api_debug_or_release_key_here" />
It can get tedious having to replace the key every time you want to debug or to generate a release build APK.

It is possible to use Gradle to automate the replacement of the Google Maps V2 API key value by using constants defined in the Gradle build types. To automate the replacement, you can do the following:
  1. In the Android app's build.gradle file, add in the following line under the debug component of buildTypes:

    resValue "string", "google_maps_v2_api_key", "your_google_maps_v2_debug_api_key_here"

    Note: replace the api key accordingly; and the constant name is google_maps_v2_api_key.
  2. Similarly, add in the following line under the release component of buildTypes:

    resValue "string", "google_maps_v2_api_key", "your_google_maps_v2_release_api_key_here"
  3. The Android app's build.gradle should look like this screenshot below:


  4. Now, in the app's AndroidManifest.xml file, replace the Google Maps V2 API key metadata value to the string constant name google_maps_v2_api_key.

    <meta-data
    android:name="com.google.android.maps.v2.API_KEY"
    android:value="@string/google_maps_v2_api_key" />
    

Now you can debug or build the Android app as per normal without manually replacing the Google Maps V2 API key.

Monday, October 28, 2019

Android Studio: resolving duplicate AndroidX and support classes errors

While migrating an Android project from the support libraries to use the AndroidX libraries, I encountered the following errors regarding "duplicate class android.support.v4.app xxxx found in modules classes.jar (androidx.core:core:1.0.0) and classes.jar (com.android.support:support-compat:26.1.0)"; even though all the Java/Kotlin/XML source code files have been replaced with the AndroidX versions and the old support libraries have been removed from the app's build.gradle file.

The screenshot below illustrates the error.


The solution I found was to set project wide gradle properties.
  1. In Android Studio, open up the project's gradle.properties file.
  2. Insert the following two lines:

    android.enableJetifier=true
    android.useAndroidX=true


  3. Save the file, select Build | Clean Project. Then select recompile again.

    The duplicate classes error messages no longer appear.|

Monday, August 12, 2019

Resolving Android Studio "Cannot fit requested classes in a single dex file" error

After I added an additional library to an Android app, this error "null, Cannot fit requested classes in a single dex file (# methods: 66445 > 65536)" occurred while trying to build the application in Android Studio, as shown in the screenshot below.
 
The solution to this is to enable multi dex support in the Android app. The following steps show how to do this:
  1. In Android Studio, add in a new dependency to the androidx.multidex:multidex library to the app's build.gradle file.

    dependencies {
    ...etc...
    implementation 'androidx.multidex:multidex:2.0.1
    ...etc...
    }

  2. Then in the same app build.gradle file, toggle true the multiDexEnabled property.

    android {
      defaultConfig {
        ...etc...
        multiDexEnabled true
        ...etc...
      }
    }

Now, compiling the Android application should no longer result in the dex error.

Monday, April 22, 2019

Migrating Android support library Renderscript code to AndroidX

Android is deprecating the Support compatibility libraries  and replacing them with the new AndroidX libraries. To aid in the migration of Android projects using the deprecated support libraries, Android Studio has a Refactor to AndroidX tool. I used that to migrate an old Android project and while it works for the most part, it did not manage to migrate the files using the support renderscript classes; I presume that is because the AndroidX namespace does not have the equivalent renderscript classes.

To complete the migration to AndroidX, I had to do the following by hand:

  1. In all the code files using the android.support.v8.renderscript.* classes, replace them to android.renderscript.* as shown below.

  2. In the app's build.gradle file, upgrade the renderscriptTargetApi level to 17 and turn off the renderscript support mode (renderscriptSupportModeEnabled to false) as shown below.


  3. Save all the files and rebuild the project.

    The project should manage to sync and build successfully.
Note: At the time of writing, Android can only compile android.renderscript.* classes into 32 bit *.bc files. This may be a problem in future as Google Play is moving to apks that support 64 bit files. 

Monday, August 20, 2018

Android Studio: Resolving a "Didn't find class "some.class.name" on path: DexPathList" error

I encountered this error message when trying to run an Android project in Android Studio.
08-15 21:05:44.338 7789-7789/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.dom925.cadmon.tampa, PID: 7789
java.lang.RuntimeException: Unable to instantiate application com.dom925.cadmon.tampa.App: java.lang.ClassNotFoundException: Didn't find class "com.dom925.cadmon.tampa.App" on path: DexPathList[[zip file "/data/app/com.dom925.cadmon.tampa-1/base.apk"],nativeLibraryDirectories=[/data/app/com.dom925.cadmon.tampa-1/lib/x86, /system/lib, /vendor/lib]]
at android.app.LoadedApk.makeApplication(LoadedApk.java:802)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5377)
at android.app.ActivityThread.-wrap2(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1545)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)



The cause to this particular problem was some missing plugins in the Android app's build.gradle file. As I was adding some Kotlin code to the project, the Gradle build system needs to recognize the Kotlin classes. If the plugins are not included, the Gradle build system will not be able to run the Kotlin code. 

The app's build.gradle file with missing Kotlin plugins
So adding in the Kotlin plugins kotlin-android and/or kotlin-android-extension as shown below solved the problem.
 

Wednesday, March 7, 2018

Fixing "Cannot resolve symbol Theme" error in Android Studio

If you have ever encountered unusual "cannot resolve symbol" messages with regards to Android resource XML files (an example is the screenshot below), which cannot be resolved by running Android Studio's Build | Clean Project or Build | Rebuild Project menu commands, then fixing the issue is very simple.


To resolve the problem, click on the Sync Project with Gradle Files icon in Android Studio, as shown in the screenshot below, or select Tools | Android | Sync Project with Gradle Files

Processing files will appear and at the end of it, the error messages no longer appear, as shown below.

Monday, October 24, 2016

Tip to speed up the Android Studio project build compilation process

Android Studio builds Android projects with the default Gradle property settings. If you find the build process taking a long time and your computer has adequate memory, it is possible to tweak the settings to allocate more memory to the build process to reduce the compilation time.

In Android Studio, open up the top level gradle.properties file to change the settings, as shown below.


In the editor, locate the commented line with the string "org.gradle.jvmargs", and make a copy of it directly underneath; then remove the # character to un-comment it.

An example of an edited gradle.properties file is shown below.

# Project-wide Gradle settings.

# IDE (e.g. Android Studio) users:
# Gradle settings configured through the IDE *will override*
# any settings specified in this file.

# For more details on how to configure your build environment visit
# http://www.gradle.org/docs/current/userguide/build_environment.html

# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
# Default value: -Xmx10248m -XX:MaxPermSize=256m
# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true

Now, the build process should complete faster.

Tuesday, August 30, 2016

Identifying deprecated classes and methods in Android Studio with "Recompile with -Xlink:deprecation"

When upgrading an Android project to a newer Android version, Google may deprecate some of the previously used Android classes and methods. By default, the gradle compilation process will only print out a summary message "Some input files use or override a deprecated API", as shown in the Android Studio screenshot below:

To enable the compilation process to print out a verbose message of the deprecated API, one or more of the build.gradle file may need to be edited to add in the -Xlint:deprecation option. In the example, the top most or project level build.gradle file was edited.


  1. In Android Studio, open up the project build.gradle file. Scroll to the allprojects section.


  2. Add in the gradle.projectsEvaluated sub section with the -Xlint:deprecation option as shown below.

  3. Save. Now when building the Android project, the deprecated API will be printed in the console.


Monday, August 1, 2016

Resolving com.android.build.api.transform.TransformException for task transformClassesWithDexForDebug

I encountered an Android Studio build exception while compiling an Android application to run on a device. The error message is shown in the screen shot below:


The message about classes and Dex gave a huge clue about the cause of the exception; I came across somewhere that there is a limit to the number of classes in a Dex file and Google Play Services use a lot of classes. My app's build.gradle has the dependency to the full com.google.android.gms:play-services:x:x:x file, as shown below.



So one method to reduce the number of classes is to use subsets of the Google Play Services library. Instead of the full com.google.android.gms:play-services dependency, my build.gradle file now has the following dependency line:
compile 'com.google.android.gms:play-services-maps:x.x.x'

Following this change, the application builds successfully, as shown in the console screen shot below.


Monday, May 9, 2016

Fix Gradle errors when upgrading old Android projects to a new Android Studio version

After upgrading my Android Studio to the latest version, I encountered problems with the Gradle version of my old Android project. The error message is saying something like the following "Gradle version 2.10 is required. Current version is 2.8. Fix Gradle wrapper and re-import project Gradle settings." A screenshot of the error is shown below.

Sometimes, clicking on the Fix hyperlink will resolve the problem; but sometimes it does not. If it does not, then it is possible to fix the problem by editing the gradle-wrapper.properties file of your project in the editor as shown below.

Simply change the version number in the distributionUrl to the new required version e.g. https\://services.gralde.org/distributions/gradle-2.10-all.zip.