Перейти к содержимому

Как обновить 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.

Gradle distribution : select Gradle wrapper that is a default-preferable option or Local installation when you want to use the specific local Gradle version.

Gradle version : if the wrapper option is selected, the latest Gradle distribution will be used unless you unselect the Auto-select option and select the specific version from the drop-down list.

Alternatively, if the Local installation was selected then the version you defined locally is used.

Auto-select : unselect this option to specify the Gradle version you want to use in your project.

Use these settings for future projects : select this checkbox to use the configured Gradle version in your future projects.

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 Control+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 in 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 ( Control+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 Distribution list select one of the following options:

Wrapper : 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 : 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.

Local installation : 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 .

Как обновить Gradle в Intellij IDEA? Ошибка Unsupported Project JDK 19

При создании проекта в IntelliJ IDEA вылезает данное окно. На данный момент самая свежая версия Gradle 7.5.1. Как обновить систему сборки в данной IDE? Возможно, нужно установить версию JDK пониже? Где можно почитать о JDK vX.X.X -> совместима с Gradle vX.X.X?

введите сюда описание изображения

Vadik Sirekanyan's user avatar

DWolf_19's user avatar

На данный момент Java 19 не поддерживается системой сборки Gradle. Об этом сказано на сайте Gradle:

A Java version between 8 and 18 is required to execute Gradle. Java 19 and later versions are not yet supported.

На той же странице есть таблица совместимости версий Gradle с версиями JDK:

Версия Java Минимальная версия Gradle
8 2.0
9 4.3
10 4.7
11 5.0
12 5.4
13 6.0
14 6.3
15 6.7
16 7.0
17 7.3
18 7.5
19 7.6

Чтобы продолжить работать с Gradle, понизьте вашу версию JDK до 18 или ниже.

Update: Gradle 7.6 поддерживает Java 19. Вы можете продолжать пользоваться Java 19, если обновите Gradle до последней версии.

Troubleshooting builds

The following is a collection of common issues and suggestions for addressing them. You can get other tips and search the Gradle forums and StackOverflow #gradle answers, as well as Gradle documentation from help.gradle.org.

Troubleshooting Gradle installation

If you followed the installation instructions, and aren’t able to execute your Gradle build, here are some tips that may help.

If you installed Gradle outside of just invoking the Gradle Wrapper, you can check your Gradle installation by running gradle —version in a terminal.

You should see something like this:

If not, here are some things you might see instead.

Command not found: gradle

If you get «command not found: gradle», you need to ensure that Gradle is properly added to your PATH .

JAVA_HOME is set to an invalid directory

If you get something like:

You’ll need to ensure that a Java Development Kit version 8 or higher is properly installed, the JAVA_HOME environment variable is set, and Java is added to your PATH .

Permission denied

If you get «permission denied», that means that Gradle likely exists in the correct place, but it is not executable. You can fix this using chmod +x path/to/executable on *nix-based systems.

Other installation failures

If gradle —version works, but all of your builds fail with the same error, it is possible there is a problem with one of your Gradle build configuration scripts.

You can verify the problem is with Gradle scripts by running gradle help which executes configuration scripts, but no Gradle tasks. If the error persists, build configuration is problematic. If not, then the problem exists within the execution of one or more of the requested tasks (Gradle executes configuration scripts first, and then executes build steps).

Debugging dependency resolution

Common dependency resolution issues such as resolving version conflicts are covered in Troubleshooting Dependency Resolution.

You can see a dependency tree and see which resolved dependency versions differed from what was requested by clicking the Dependencies view and using the search functionality, specifying the resolution reason.

troubleshooting dependency management build scan

The actual build scan with filtering criteria is available for exploration.

Troubleshooting slow Gradle builds

For build performance issues (including “slow sync time”), see improving the Performance of Gradle Builds.

Android developers should watch a presentation by the Android SDK Tools team about Speeding Up Your Android Gradle Builds. Many tips are also covered in the Android Studio user guide on optimizing build speed.

Debugging build logic

Attaching a debugger to your build

You can set breakpoints and debug buildSrc and standalone plugins in your Gradle build itself by setting the org.gradle.debug property to “true” and then attaching a remote debugger to port 5005. You can change the port number by setting the org.gradle.debug.port property to the desired port number.

To attach the debugger remotely via network, you need to set the org.gradle.debug.host property to the machine’s IP address or * (listen on all interfaces).

In addition, if you’ve adopted the Kotlin DSL, you can also debug build scripts themselves.

The following video demonstrates how to debug an example build using IntelliJ IDEA.

Adding and changing logging

In addition to controlling logging verbosity, you can also control display of task outcomes (e.g. “UP-TO-DATE”) in lifecycle logging using the —console=verbose flag.

You can also replace much of Gradle’s logging with your own by registering various event listeners. One example of a custom event logger is explained in the logging documentation. You can also control logging from external tools, making them more verbose in order to debug their execution.

Additional logs from the Gradle Daemon can be found under $GRADLE_USER_HOME/daemon/<gradle-version>/ .

Task executed when it should have been UP-TO-DATE

—info logs explain why a task was executed, though build scans do this in a searchable, visual way by going to the Timeline view and clicking on the task you want to inspect.

troubleshooting task execution build scan

You can learn what the task outcomes mean from this listing.

Debugging IDE integration

Many infrequent errors within IDEs can be solved by «refreshing» Gradle. See also more documentation on working with Gradle in IntelliJ IDEA and in Eclipse.

Refreshing IntelliJ IDEA

NOTE: This only works for Gradle projects linked to IntelliJ.

From the main menu, go to View > Tool Windows > Gradle . Then click on the Refresh icon.

troubleshooting refresh intellij

Refreshing Eclipse (using Buildship)

If you’re using Buildship for the Eclipse IDE, you can re-synchronize your Gradle build by opening the «Gradle Tasks» view and clicking the «Refresh» icon, or by executing the Gradle > Refresh Gradle Project command from the context menu while editing a Gradle script.

troubleshooting refresh eclipse

Troubleshooting daemon connection issues

If your Gradle build fails before running any tasks, you may be encountering problems with your network configuration. When Gradle is unable to communicate with the Gradle daemon process, the build will immediately fail with a message similar to this:

We have observed this can occur when network address translation (NAT) masquerade is used. When NAT masquerade is enabled, connections that should be considered local to the machine are masked to appear from external IP addresses. Gradle refuses to connect to any external IP address as a security precaution.

The solution to this problem is to adjust your network configuration such that local connections are not modified to appear as from external addresses.

You can monitor the detected network setup and the connection requests in the daemon log file ( $GRADLE_USER_HOME/daemon/<Gradle version>/daemon-<PID>.out.log ).

Getting additional help

If you didn’t find a fix for your issue here, please reach out to the Gradle community on the help forum or search relevant developer resources using help.gradle.org.

If you believe you’ve found a bug in Gradle, please file an issue on GitHub.

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

При запуске нового проекта я получаю сообщение неподдерживаемый JDK. Использование Gradle 7.1. Я хочу обновить Gradle по умолчанию до 7.3-rc-1.

Однако я просто не могу найти, где это можно сделать, кроме конкретного проекта. Я не уверен, где IntelliJ получает свою версию Gradle, и в прошлом она автоматически обновлялась.

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

Как изменить версию «оболочки gradle по умолчанию» в IntelliJ IDEA?

Я хочу использовать Gradle 1.10 вместо 1.9. Кажется, я не могу найти, где это изменить.

Если я поставлю это:

в моем build.gradle и rebuild он снова построен с Gradle 1.9 (так что на самом деле ничего не происходит).

Кажется, это все настройки: (и раздел справки IntelliJ о Gradle совсем не помогает :() Что значит «не настроено для текущего» проекта?

Самый простой способ — выполнить следующую команду из командной строки (см. Обновление Gradle Wrapper в документации):

Более того, вы можете использовать —distribution-type параметр со значением bin или, all чтобы выбрать тип распределения. Используйте all тип распространения, чтобы избежать подсказки от IntelliJ IDEA или Android Studio, которая предложит вам загрузить Gradle с исходниками:

Или вы можете создать индивидуальную wrapper задачу

и беги ./gradlew wrapper .

Откройте файл gradle/wrapper/gradle-wrapper.properties в своем проекте. Измените версию в, distributionUrl чтобы использовать версию, которую вы хотите использовать, например,

Я просто хотел сказать, что ударил это после обновления компонентов Android Studio.

Для меня сработало открытие gradle-wrapper.properties и обновление используемой версии gradle. На данный момент для моих проектов строка гласит:

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

Чтобы ввести его без команды:

перейти к-> gradle/wrapper/gradle-wrapper.properties URL-адрес распространения и измените его на обновленную версию zip-архива

В build.gradle оном wrapper

Задача-оболочка в gradle вызывается, если используется команда gradlew, если вы используете команду gradle для создания задачи-оболочки, не вызывается. Итак, есть два способа изменить версию Gradle.

Используйте команду ‘gradlew build’, эта команда вызовет указанную вами задачу оболочки. Эта задача изменит параметр distributionUrl в файле gradle-wrapper.properties и автоматически загрузит нужную вам версию gradle. Пример distributionUrl в файле для версии 4.2. distributionUrl = https: //services.gradle.org/distributions/gradle-4.2-bin.zip

Если вы не используете оболочку gradle, просто загрузите нужную версию gradle и установите путь к переменной среды, а также покажите ее IDEA.

ПРОграммирование под 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 не будет опубликован. Обязательные поля помечены *