Как обновить gradle в intellij idea
Перейти к содержимому

Как обновить gradle в intellij idea

  • автор:

Gradle

IntelliJ IDEA supports a fully-functional integration with Gradle that helps you automate your building process. You can easily create a new Gradle project, open and sync an existing one, work with several linked projects simultaneously, and manage them.

You can also create a Gradle project and store it in the WSL environment or open it from the WSL file system. For more information, refer to the WSL section.

Create a new Gradle project

Launch the New Project wizard. If no project is currently opened in IntelliJ IDEA, click New Project on the welcome screen. Otherwise, select File | New | Project from the main menu.

Name the new project and change its location if necessary.

Select the Create Git repository to place the new project under version control.

You will be able to do it later at any time.

Select a language that you want to use in your project. Click if you want to add other languages available via plugins.

Select Gradle in the list of Build system .

Specify project’s SDK (JDK) or use the default one.

If you don’t have a JDK on your machine, IntelliJ IDEA can quickly download the JDK for you.

The Gradle project sync will wait until the JDK is downloaded.

The selected Add sample code option will create a file with a basic code sample.

Select Gradle DSL . You can select Groovy for traditional syntax or Kotlin as an alternative.

In Advanced Settings , specify the fields which resemble the Maven coordinates. These settings might be helpful if you decide to deploy your project to a Maven repository. The fields you specify are added to the build.gradle file.

GroupId — groupId of the new project. You can omit this field if you plan to deploy your project locally.

ArtifactId — artifactId that is added as a name of your new project.

Version — version of the new project. By default, this field is specified automatically.

For more information on Maven coordinates, see Maven naming conventions.

Create a Java EE project with Gradle as a build tool

Launch the New Project wizard. If no project is currently opened in IntelliJ IDEA, click New Project on the welcome screen. Otherwise, select File | New | Project from the main menu.

Under the Generators section, select Jakarta EE .

Configure your project selecting the appropriate options such as your project’s name, location, language, and select Gradle as your build tool.

IntelliJ IDEA creates a Gradle project with the dedicated Gradle tool window and adds necessary dependencies.

For the more detailed information, refer to Tutorial: Your first Java EE application.

Open an existing Gradle project

If you have the offline mode enabled in your project, the opening or re-importing of the project might fail. To fix the issue, disable the offline mode and re-import your project.

If no project is currently opened in IntelliJ IDEA, click Open on the welcome screen. Otherwise, select File | Open from the main menu.

If you have some custom plugins that require you to import your project from the IntelliJ IDEA model, press Ctrl+Shift+A and search for the Project from Existing Sources action.

In the dialog that opens, select a directory containing a Gradle project and click OK .

IntelliJ IDEA opens and syncs the project in the IDE.

If you need to adjust the Gradle settings options, refer to Gradle settings.

Check Gradle JVM and language level

Gradle JVM : when IntelliJ IDEA opens the Gradle project, it checks the gradle.properties file for the appropriate JVM version specified in org.gradle.java.home and uses it for the project. If it is not specified, then the project SDK is used. Alternatively, you can use the Gradle settings to configure the Gradle JVM.

Language level : the language level settings are applied for a source root or for a module. If a Gradle project has a single linked project then the project default language level is set to the minimum language level among the module language levels. The module language level is set to sourceCompatibility in the build.gradle file.

The preview part is set to the conjunction of preview flags of the module source sets. The source set module language level is set to the corresponding combination of sourceCompatibility property and —enable-preview flag.

Link a Gradle project to an IntelliJ IDEA project

You can have multiple Gradle projects inside one IntelliJ IDEA project. It might be helpful if you keep parts of code in different projects, have some legacy projects on which you need to work, have Gradle composite build or work with microservices. You can link such projects in IntelliJ IDEA and manage them simultaneously.

When you open a Gradle project, the link of the project is established automatically and the Gradle tool window is enabled.

If an IntelliJ IDEA project is not linked to a Gradle project, then the Gradle tool window is disabled. In this case, IntelliJ IDEA displays a message with a link that quickly lets you reimport your Gradle project and enable the Gradle tool window. If the Gradle tool window is active, then you have at least one Gradle project linked.

Open the Gradle tool window.

In the Gradle tool window, click to attach a Gradle project.

In the dialog that opens, select the desired build.gradle file, and click OK .

In the Import Module from Gradle window, specify options for the Gradle project that you are trying to link and click OK .

The project is linked. The Gradle tool window shows the toolbar and a tree view of Gradle entities.

If you need to link back the previously unlinked project, in the Project tool window, right-click the added build.gradle or if it is a Gradle Kotlin module the build.gradle.kts file and select Import Gradle Project .

Add a new Gradle module to an existing Gradle project

You can add a Gradle module to a project in which you are already working.

In a project, from the main menu, select File| New | Module to open the New Module wizard.

If the existing project is not the Gradle project then the process of adding a module is the same as Creating a new Gradle project. If the existing project is a Gradle project then the process of adding a new module is shorter. You need to specify the name of your module in the ArtifactId field. The rest of the information is added automatically and you can use either the default settings or change them according to your preferences. Also, note that Add as module to field, by default, displays the name of your project to which you are trying to add a module. You can click to select a different name if you have other linked Gradle projects.

Convert a regular project into a Gradle project

Open your project in IntelliJ IDEA.

In the Project tool window, right-click the name of your project and select New | File .

In the dialog that opens enter build.gradle and click OK .

Open the build.gradle file in the editor, add the information you need and re-open your project. The following minimal information should be included into the project’s build script file:

As soon as you create a build.gradle file, IntelliJ IDEA recognizes the Gradle build script and displays a notification suggesting to load the project as Gradle. After you load the project, IntelliJ IDEA enables the Gradle tool window.

We also recommend that you add the settings.gradle file to your project and add rootProject.name = ‘projectName’ to it. Where ‘projectName’ would be the name of your project.

Access the Gradle settings

Use the Gradle settings to configure the build and run actions for each linked Gradle project, a Gradle version, importing of the project’s changes, and so on.

In the Settings dialog ( Ctrl+Alt+S ), go to Build, Execution, Deployment| Gradle .

Gradle settings

Click on the toolbar, in the Gradle tool window to access the Gradle settings.

On the Gradle settings page, configure the available options and click OK to save the changes.

Configure a Gradle version for a project

IntelliJ IDEA lets you use different options to configure a Gradle version for your Gradle project. You can use the default Gradle wrapper, use a Gradle wrapper as a task, or configure a local Gradle distribution.

Select in the Gradle tool window to quickly access the Gradle settings page.

In the Use Gradle from list select one of the following options:

‘gradle-wrapper.properties’ file : this is a recommended default option that uses Gradle wrapper.

In this case you delegate the update of Gradle versions to Gradle and get an automatic Gradle download for the build. This option also lets you build with a precise Gradle version. The Gradle version is saved in the gradle-wrapper.properties file in the gradle directory of your project and helps you eliminate any Gradle version problems.

‘wrapper’ task in Gradle build script : select this option to configure a Gradle wrapper according to the wrapper task configuration. It might be convenient if you prefer to control which Gradle version to use in the project.

If you used the default Gradle wrapper option and then switched to the Gradle wrapper task configuration, changes you made in the task automatically update during the project import.

Specified location : select this option if you want to manually download and use a specific Gradle version. Specify the location of your Gradle installation and JVM under which IntelliJ IDEA will run Gradle when you import the specified Gradle project and when you execute its tasks.

Click OK to save the changes.

Add VM options for the Gradle project

You can specify VM options for your Gradle project using the gradle.properties file.

Create or open your Gradle project.

In the Project tool window, right-click the project and from the context menu, select New | File .

In the New File dialog, enter gradle.properties as a filename and click OK .

Open the created file in the editor and add the VM options you need.

For more information, refer to the Gradle documentation.

Increase daemon heap size

You can adjust the existing Gradle daemon heap size for your project using the gradle.properties file.

Create or open your Gradle project.

In the Project tool window, right-click the project and from the context menu, select New | File .

How to change the version of the 'default gradle wrapper' in IntelliJ IDEA?

I want to use Gradle 1.10 instead of 1.9. I cannot seem to find where to change this.

in my build.gradle and rebuild, it is built with Gradle 1.9 again (so nothing actually happens).

These seem to be all the settings: (and IntelliJ’s help section about Gradle doesn’t help at all 🙁 ) What does "not configured for the current" project mean?

Mahozad's user avatar

Bloke's user avatar

11 Answers 11

The easiest way is to execute the following command from the command line (see Upgrading the Gradle Wrapper in documentation):

Moreover, you can use —distribution-type parameter with either bin or all value to choose a distribution type. Use all distribution type to avoid a hint from IntelliJ IDEA or Android Studio that will offer you to download Gradle with sources:

Or you can create a custom wrapper task

and run ./gradlew wrapper .

Open the file gradle/wrapper/gradle-wrapper.properties in your project. Change the version in the distributionUrl to use the version you want to use, e.g.,

I just wanted to chime in that I hit this after updating Android Studio components.

What worked for me was to open gradle-wrapper.properties and update the gradle version used. As of now for my projects the line reads:

./gradlew wrapper —gradle-version=5.4.1 —distribution-type=bin

To input it without command:

go to-> gradle/wrapper/gradle-wrapper.properties distribution url and change it to the updated zip version

You can set the version of Gradle generated by the wrapper task.
Note that this solution is in Kotlin DSL (build.gradle.kts).

Put this code in your top-level build.gradle.kts file:

Whenever you want to change Gradle version:

  1. Update the version above to your desired version
  2. Execute Gradle wrapper task: ./gradlew wrapper
  3. Sync the IDE (from Gradle sidebar -> reload icon)

Mahozad's user avatar

I was facing same issue for changing default gradle version from 5.0 to 4.7, Below are the steps to change default gradle version in intellij enter image description here
1) Change gradle version in gradle/wrapper/gradle-wrapper.properties in this property distributionUrl

2) Hit refresh button in gradle projects menu so that it will start downloading new gradle zip version

The ‘wrapper’ task in gradle is called if gradlew command is used, if you use gradle command to build the wrapper task is not called. So, there are two ways you can change your gradle version.

Use ‘gradlew build’ command, this command will call the wrapper task that you mentioned. That task will change the ‘distributionUrl’ parameter in gradle-wrapper.properties file and it will automatically download the gradle version you want. Example distributionUrl in the file for version 4.2. distributionUrl=https://services.gradle.org/distributions/gradle-4.2-bin.zip

If you are not using gradle wrapper simply download the version of the gradle you want and set environment variable path and also show it to IDEA.

How to Efficiently Upgrade to Latest Version of Gradle

Gradle is a great build tool which allows you to write versatile build code to achieve whatever you want. The biggest drawback for me is the velocity of the Gradle releases and the corresponding breaking changes. You may say that one major release a year is ok but I currently manage tens of small open-sourced projects for me build script is something I should barely be touched except adding dependencies and new subprojects. So the need to upgrade happens only once in a couple of years and obviously not the only one as most of the projects on GitHub are still using Gradle 4.x:

I usually face a storm of issues from the build when I try to get the latest possible Gradle version working. Jumping form a very old version to the newest one is obviously not a good way to go. It's always better to move stepwise so I took GitHub Actions for a rescue.

Stepwise Gradle Upgrade with Gradle Actions

Following steps could be achieved with any continuous integration tool but GitHub Actions allow to run much more parallel jobs at once than other available CI servers I know (at least for free).

Setting up GitHub Action Workflow

The idea is to run your project against every possible minor version of Gradle between the one currently present in the project ( 4.7 ) and the latest one ( 6.0.1 as a time of writing) to find you the which version still working with the current setup. You may argue that it would be enough to just use the major versions but there might be some consequences (e.g. upgrade of static analysis tools) which may also happen in minor versions.

We start with a workflow file located in .github/workflows/gradle.yml :

The workflow checks out the code then it installs Java and it runs Gradle check task for all versions we are interested in. This may not fully guarantee that the other tasks such as deployment will work but it should detect most of the problems.

When all the jobs are finished in my project I have got the following results:

The results show me that the latest version I can use is 4.10.3 . I suggest you to use SDKMAN to manage the local versions of frameworks so you can upgrade the Gradle wrapper by using the latest passing version and running the wrapper command.

You should also remove the already passing version numbers from the matrix because they are no longer needed:

Then commit the changes in case of that you will need to revert some changes.

Stepwise Migration

Now there's a time to fix the problem for the first failing version. You may get the good picture of what's wrong simply by expanding the outputs in the GitHub Actions console. Also, the deprecation notes from the last working version may help. If the logs are not descriptive enough you can always use SDKMAN once again to run the build locally against different version than the wrapper one.

I will summarize some changes that my project required in the next section but each project is quite unique so you will probably face a suite of very different issues depending on which features and plugins you are using.

You repeat the steps unless you reach only the currently latest released version

  1. fix the build problems for the current version
  2. push the changes to GitHub
  3. identity the new latest version which passes
  4. update the Gradle wrapper to the latest passing version
  5. remove the already passing version numbers from the workflow file
  6. push the changes to GitHub
  7. return to step 1 if required

Once you reach the latest version you can easily remove the matrix and gradle-version from the workflow file:

To be sure that you won't fall behind the Gradle releases I would suggest you create a separate workflow file gradle-versions-watchdog.yml which will be triggered regularly. scheduled configuration will run once a month which is useful for projects which barely changes but you still want to keep Gradle versions up to date as rc is the latest release candidate version which is currently available.

The Story of One Upgrade

I have created this guide based on my experience of upgrading Gradle for Micronaut Libraries project. The build was pretty simple and consists of

  • running a static analysis using CheckStyle and CodeNarc
  • running all tests with aggregated JaCoCo coverage
  • publishing the coverage to Coveralls.io
  • generating the guide from Asiidoctor files
  • publishing the guide to GitHub Pages
  • publishing the artefacts to Bintray

These are pretty common tasks which you can find in most of the open-source projects. There is even a great bunch of plugins called Kordamp which simplifies most of the tasks mentioned. It also provides test aggregation task which wast the reason I have been doing the migration.

I was expecting a lot of problems with the incompatible plugins but I only had to give up on JaCoCo Full Report Plugin which is no longer supported in Gradle 6. I was willing to sacrifice that one as I want to migrate to Kordamp once the upgrade is finished and it provides the same functionality.

So the first issue was pretty trivial to fix — since 5.x there are no special characters allowed in the project name so I had to fix these.

Another issue was caused by the upgrade of CheckStyle with breaking changes in the configuration file. And of course, fixing the new default checks such as parentheses around lambda parameters.

A different story is the changed dependency resolution mechanism. To make the story short — Gradle 5.x won't resolve the transitive dependencies correctly for libraries published with Gradle 4.x and older as they used to be published with a wrong Maven scope.

The last step was to migrate the behaviour of the annotation processors. The annotation processors must be now declared is special configurations annotationProcessor and testAnnotationProcessor .

This was the last step of the upgrade which were needed for the particular project. There are no significant notable improvements but on the other hand, there are significant losses in terms of functionality which is no longer supported and needs to be migrated such as publishing the code coverage.

Summary

Keeping the build tool up to date is an unimportant task for many small projects. The gains are not obvious compared to the time which is spent on performing the upgrade and which can be spent on some more useful tasks. It can easily happen that you will have to sacrifice some of the functionality of your current build as there is also a lot of open-source plugins which failed to keep the pace with Gradle's release cycle.

I'm currently putting hope to the Kordamp plugin suite which eliminates part of the flexibility of Gradle but should builds which are easier to maintain and less vulnerable to break during the upgrades. I will summarize the migration in another post if I succeed.

Revision History

2019–12–12: Suggested to create separate workflow file for regular Gradle RC checks.

ПРОграммирование под Android

IntelliJ IDEA захотела заново скачать дистриб Gradle, хотя он уже был на компе, от предыдущей версии. И ладно бы начала скачивать новую версию, так нет же, качает старую, такую же как уже есть.

I00017

На этом мое терпение лопнуло и я решил разобраться с Gradle раз и на всегда!

Идем на сайт Gradle и качаем дистриб. На данный момент это версия 2.3, а IDEA качала с этого же сайта более старую версию 2.2.1

I00019

Дистриб из себя представляет просто архив gradle-2.3-all.zip. Я его разархивировал в C:\gradle-2.3

I00020

Далее идем в настройки IntelliJ IDEA и делаем раз, два, три, четыре…

I00021

Теперь, чтобы старые файлы Gradle не занимали место, все их можно удалить из каталога

C:\Users\<User Name>\.gradleIntelliJIdea

Хотя это я у себя настроил такой каталог, у вас может быть просто .gradle

Но и после этого Gradle еще сильно тормозил собирая проекты. Чтобы придать ему ускорение, надо немного изменить файл настроек gradle.properties в проекте

I00022

После всех этих манипуляций, при попытку установить (запустить) приложение на виртуальное устройство может выскочить ошибка

I00024

INSTALL_FAILED_UID_CHANGED

Это можно вылечить подправив параметр applicationId в файлике проекта

I00023

Про эту ошибочку можно еще почитать тут и чтобы понять что происходит тут.

Вкратце это произошло потому, что приложение не корректно было удалено и оставило свою папку в каталоге /data/data

Так же эту проблему можно решить удалив каталог программы с устройства через adb shell.

Утилитка adb живет по пути C:\android-sdk-windows\platform-tools ну по крайней мере у меня, у вас может быть другой путь. Запускаем ее в командной строке с параметром devices

I00025

Далее даем команду adb remount, чтобы смонтировать файловую систему устройства с правами на запись.

Далее запускаем shell на устройстве

I00027

И далее смотрим содержимое каталога /data/data командой ls /data/data

I00028

Вывод у этой команды достаточно длинный, так как выводятся все приложения установленные на устройстве

Ну и далее удаляем каталог программы, которая не может установиться по запуску из IntelliJ IDEA

I00029

Удаляем командой rm –r , так как могут быть вложенные каталоги.

На заметку некоторые adb команды

adb devices – список устройств которые уже прикреплены к компьютеру
adb install <packagename.apk> – позволяет установить приложение на устройство
adb remount – размонтирует систему в режим записи – позволяет менять системные файлы на устройстве используя ADB
adb push <localfile> <location on your phone> – позволяет загружать файлы в файловую систему устройства
adb pull <location on your phone> <localfile> – позволяет скачивать файлы с файловой системы устройства
adb logcat – начинает дампить отладочную информацию с устройства в консоль – полезно для отладки приложений
adb shell <command> – бросает вас в базовые shell команды linux’а без параметров, или позволяет непосредственно запускать команды

Хотя там, почему-то далеко не все команды adb перечислены.

Полную справку по командам можно получить через сам adb. Просто дав эту команду безе параметров.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *