Task not found in root project - android

I am confused by gradle build lifecycle for a few days. Refer tells me
A Gradle build has three distinct phases.
Initialization
Configuration
Execution
Is task creation in the third step? If so, how does gradle find all tasks in a project object?
Here is an example.
rootporject
|----app
|----build.gradle
|----checkstyle.gradle
The build.gradle is as simple as normal.checkstyle.gradle file has a task. Here is its content.
apply plugin: 'checkstyle'
task checkstyle(type:Checkstyle) {
description 'Runs Checkstyle inspection against girl sourcesets.'
group = 'Code Quality'
configFile rootProject.file('checkstyle.xml')
ignoreFailures = false
showViolations true
classpath = files()
source 'src/main/java'
}
After ./gradlew -q tasks, there is no task checkstyle.
But if I remove the definition into build.gradle, I get it.
Is there anything wrong?Thanks in advance.
Edit
From doc
There is a one-to-one relationship between a Project and a build.gradle file.

You haven't applied your other script.
In your build.gradle you should add an apply from: 'checkstyle.gradle'.

Related

The use of safeArgs in Android Studio is causing an error and I cannot build the project

I am trying to build my project in Kotlin and I am getting this error:
Execution failed for task ':app:generateSafeArgsDebug'.
Could not read 'F:\Program Files\Android Projects\CityOnApp\crowdapps-mobile-android\app\build\intermediates\metadata_application_id\debug\application-id.txt' as it does not exist.
and when I added in Settings > Build, Execution, Deployment > Compiler > Command Line Options :
--stacktrace --debug -Pandroid.debug.obsoleteApi=true, then I got :
[ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]
Execution failed for task ':app:generateSafeArgsDebug'.
Could not read 'F:\Program Files\Android Projects\CityOnApp\crowdapps-mobile-android\app\build\intermediates\metadata_application_id\debug\application-id.txt' as it does not exist.
I checked the path and the file does not exist there!
I have the latest version in Kotlin and Android Studio.
What I tried and did not work is :
clean build and rebuild/ build
downgrading the version of Android Studio
deleting the .gradle file from the root directory
plugins {
id 'com.android.application' version '7.1.0' apply false
id 'com.android.library' version '7.1.0' apply false
id 'org.jetbrains.kotlin.android' version '1.6.10' apply false
id 'androidx.navigation.safeargs.kotlin' version '2.4.1' apply false
}
To add Safe Args to your project, include the following classpath in your top level build.gradle file:
buildscript {
repositories {
google()
}
dependencies {
def nav_version = "2.3.4"
classpath "androidx.navigation:navigation-safe-args-gradle-plugin:$nav_version"
}
}
You must also apply one of two available plugins.
To generate Java language code suitable for Java or mixed Java and Kotlin modules, add this line to your app or module's build.gradle file:
apply plugin: "androidx.navigation.safeargs"
Alternatively, to generate Kotlin code suitable for Kotlin-only modules add:
apply plugin: "androidx.navigation.safeargs.kotlin"
You must have android.useAndroidX=true in your gradle.properties file as per Migrating to AndroidX.
Source : Official Documentation
Try upgrading/downgrading the gradle plugin.
classpath 'com.android.tools.build:gradle:x.x.x'
Try upgrading/dowgrading gradle wrapper properties
distributionUrl=https\://services.gradle.org/distributions/gradle-x.x.x-bin.zip
Try invalidating caches in Android Studio through the file menu.
Try running Android Studio in admin/sudo.
Check your (git/local)history to see if anything changed that could cause this.
If all else fails, reinstall Android Studio and freshly import your project entirely.
To add safe-args
add this dependencies to build.gradle(project) before plugins{}block on the top
buildscript {
repositories {
google()
}
dependencies {
classpath("androidx.navigation:navigation-safe-args-gradle-plugin:2.4.2")
}}
this to the build.gradle(Module) file inside plugin{}block
id("androidx.navigation.safeargs.kotlin")
After adding Rebuild the project this will implement the safe-args

Checkstyle Plugin does not add gradle tasks

i want to use checkstyle plugin in my gradle project, the gradle documentation says that it will add a few tasks:
https://docs.gradle.org/current/userguide/checkstyle_plugin.html
checkstyleMain, checkstyleTest, checkstyleSourceSet
I added this into my app build.gradle file:
apply plugin: 'checkstyle'
I want to run gradle task from cmd to perform code style check, but there are no one checkstyle task. I checked the whole list by typing:
./gradlew tasks
I also tried to add checkstyle jar as library dependency to app module.
Can anyone tell me what i am doing wrong and how can i get my checkstyle tasks?
Well, the checkstyle plugin adds its tasks in the Other tasks virtual task group. Those are really the tasks which have not been assigned to a task group. So, they are shown only when you run ./gradlew tasks --all (note the --all).
Complete working build.gradle:
apply plugin: 'java';
apply plugin: 'checkstyle';
Then run ./gradlew tasks --all, output:
<...snip...>
Other tasks
-----------
checkstyleMain - Run Checkstyle analysis for main classes
checkstyleTest - Run Checkstyle analysis for test classes
<...snip...>
If you want the Checkstyle tasks to appear without --all, then assign them to a task group, for example:
tasks.withType(Checkstyle).each {
it.group = 'verification'
}
Looking at other Android projects, built with Gradle, that run checkstyle (thanks Square) I found that I needed to do some setup for the task to appear. Without the task declaration I would still see my initial error.
build.gradle:
...
apply plugin: 'checkstyle'
...
checkstyle {
configFile rootProject.file('checkstyle.xml')
ignoreFailures false
showViolations true
toolVersion = "7.8.1"
}
task Checkstyle(type: Checkstyle) {
configFile rootProject.file('checkstyle.xml')
source 'src/main/java'
ignoreFailures false
showViolations true
include '**/*.java'
classpath = files()
}
// adds checkstyle task to existing check task
afterEvaluate {
if (project.tasks.getByName("check")) {
check.dependsOn('checkstyle')
}
}
You also need a checkstyle configuration file, either by placing one at the default location as documented or by configuring it explicitly.
For example:
checkstyle {
config = resources.text.fromFile('config/checkstyle.xml')
}

Could not find method android() for arguments

I've been trying to import a project to Android Studio and this is where I am stuck, there is a similar question on Stack Overflow but it did not provide a solution to my particular error.
This is my error log:
C:\<some location>\build.gradle
Error:(24, 1) A problem occurred evaluating root project '<project name>'.
> Could not find method android() for arguments [build_4fli1jm76ubcnxesnhqnhie47$_run_closure3#6e71db85] on root project '<project name>'.
Information:BUILD FAILED
The Gradle sync messages are:
Error:(24, 0) Gradle DSL method not found: 'android()' Possible
causes:The project 'PoojaPeople' may be using a version of
Gradle that does not contain the method. Gradle settingsThe build file
may be missing a Gradle plugin. Apply
Gradle plugin
I'm not too sure where exactly this method android() is located. If it is the one located in Application's build.gradle file, I still don't exactly know where to go from here. Any help is appreciated.
My build.gradle is
buildscript {
repositories {
maven { url "http://dl.bintray.com/populov/maven" }
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
maven { url "http://dl.bintray.com/populov/maven" }
mavenCentral()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
android {
compileSdkVersion 17
buildToolsVersion '23.0.0'
}
dependencies {
compile files('app/libs/junit-4.12-JavaDoc.jar')
}
apply plugin: 'maven'
You are using the wrong build.gradle file.
In your top-level file you can't define an android block.
Just move this part inside the module/build.gradle file.
android {
compileSdkVersion 17
buildToolsVersion '23.0.0'
}
dependencies {
compile files('app/libs/junit-4.12-JavaDoc.jar')
}
apply plugin: 'maven'
My issue was inside of my app.gradle. I ran into this issue when I moved
apply plugin: "com.android.application"
from the top line to below a line with
apply from:
I switched the plugin back to the top and violá
My exact error was
Could not find method android() for arguments [dotenv_wke4apph61tdae6bfodqe7sj$_run_closure1#5d9d91a5] on project ':app' of type org.gradle.api.Project.
The top of my app.gradle now looks like this
project.ext.envConfigFiles = [
debug: ".env",
release: ".env",
anothercustombuild: ".env",
]
apply from: project(':react-native-config').projectDir.getPath() + "/dotenv.gradle"
apply plugin: "com.android.application"
guys. I had the same problem before when I'm trying import a .aar package into my project, and unfortunately before make the .aar package as a module-dependence of my project, I had two modules (one about ROS-ANDROID-CV-BRIDGE, one is OPENCV-FOR-ANDROID) already. So, I got this error as you guys meet:
Error:Could not find method android() for arguments [org.ros.gradle_plugins.RosAndroidPlugin$_apply_closure2_closure4#7e550e0e] on project ‘:xxx’ of type org.gradle.api.Project.
So, it's the painful gradle-structure caused this problem when you have several modules in your project, and worse, they're imported in different way or have different types (.jar/.aar packages or just a project of Java library). And it's really a headache matter to make the configuration like compile-version, library dependencies etc. in each subproject compatible with the main-project.
I solved my problem just follow this steps:
① Copy .aar package in app/libs.
② Add this in app/build.gradle file:
repositories {
flatDir {
dirs 'libs' //this way we can find the .aar file in libs folder
}
}
③ Add this in your add build.gradle file of the module which you want to apply the .aar dependence (in my situation, just add this in my app/build.gradle file):
dependencies {
compile(name:'package_name', ext:'aar')
}
So, if it's possible, just try export your module-dependence as a .aar package, and then follow this way import it to your main-project. Anyway, I hope this can be a good suggestion and would solve your problem if you have the same situation with me.
This error appear because the compiler could not found "my-upload-key.keystore" file in your project
After you have generated the file you need to paste it into project's andorid/app folder
this worked for me!

Aggregate Javadoc for Android project with multiple library modules

I've gone through almost entire Internet in search of a way how to aggregate Javadocs in the project consisting of separate library modules into single Javadoc.
There is a plugin that apparently allows to do that:
https://github.com/nebula-plugins/gradle-aggregate-javadocs-plugin
However, if I run the command specified by the plugin Gradle finds the task and executes it but no output directory is generated.
Any help how to build single Javadoc from multiple modules much appreciated.
I managed to get it working some time ago, apologies for a late response. The solution for aggregatable Javadoc creation is the following:
In each of the subprojects maintained within the project create a task generating the Javadoc:
android.libraryVariants.all { variant ->
task("generate${variant.name.capitalize()}Javadoc", type: Javadoc) {
destinationDir = project.file("$project.projectDir/javadoc/$project.PROJECT_NAME") //Project name in the Project's gradle.properties
title = "A title of my project - $project.PROJECT_VERSION_NAME" //Project version name in the Project's gradle.properties
description "Generates Javadoc for $variant.name."
source = variant.javaCompile.source
ext.androidJar ="${android.sdkDirectory}/platforms/${android.compileSdkVersion}/android.jar"
classpath = files(variant.javaCompile.classpath.files) + files(ext.androidJar) + project.files(android.getBootClasspath().join(File.pathSeparator))
options {
memberLevel = org.gradle.external.javadoc.JavadocMemberLevel.PUBLIC //change the modifier according to your needs
links "http://docs.oracle.com/javase/8/docs/api/"
linksOffline "http://d.android.com/reference", "${android.sdkDirectory}/docs/reference"
}
exclude '**/BuildConfig.java'
exclude '**/R.java'
}
task("bundle${variant.name.capitalize()}Javadoc", type: Jar) {
baseName = "Compass API - ($version)"
description "Bundles Javadoc into zip for $variant.name."
classifier = "javadoc"
from tasks["generate${variant.name.capitalize()}Javadoc"]
}
}
The configuration above adds a Javadoc generation task for each buildVariant of your subproject. At this point you can you can generate Javadoc for each module separately by typing
gradle :myRootProject:mySubproject:generateDebugJavadoc
gradle :myRootProject:mySubproject:generateReleaseJavadoc
gradle :myRootProject:mySubproject:generateMyFancyFlavourDebugJavadoc
gradle :myRootProject:mySubproject:generateMyFancyFlavourReleaseJavadoc
If you use JRE 8 the following configuration disables errors raised by doclint during the Javadoc build (explanation in greater detail here)
if (JavaVersion.current().isJava8Compatible()) {
tasks.withType(Javadoc) {
// disable the crazy super-strict doclint tool in Java 8
//noinspection SpellCheckingInspection
options.addStringOption('Xdoclint:none', '-quiet')
}
}
To aggregate Javadocs of each submodules into a single one create a Plugin in to build.gradle which will add a task to the submodule a partial Javadoc generation of which you are interested in:
class JavadocAggregationPlugin implements Plugin<Project> {
static final String AGGREGATE_JAVADOCS_TASK_NAME = 'aggregateJavadocs'
#Override
void apply(Project project) {
Project rootProject = project.rootProject
rootProject.gradle.projectsEvaluated {
Set<Project> librarySubprojects = getLibraryProjects(rootProject)
if (!librarySubprojects.isEmpty()) {
rootProject.task(AGGREGATE_JAVADOCS_TASK_NAME, type: Javadoc) {
description = 'Aggregates Javadoc API documentation of all subprojects.'
group = JavaBasePlugin.DOCUMENTATION_GROUP
dependsOn librarySubprojects.generateReleaseJavadoc //please note that generateReleaseJavadoc is the name of the separate Javadoc generation task in each library module
source librarySubprojects.generateReleaseJavadoc.source
destinationDir rootProject.file("$rootProject.buildDir/docs/javadoc") //Javadoc destination directory
classpath = rootProject.files(librarySubprojects.generateReleaseJavadoc.classpath)
}
}
}
}
private Set<Project> getLibraryProjects(Project rootProject) {
rootProject.subprojects.findAll { subproject -> subproject.plugins.findPlugin("com.android.library") } //In this case every library module is selected
}
}
Finally, include your plugin to the gradle configuration in the Project's build.gradle below your plugin definition.
apply plugin: JavadocAggregationPlugin
By doing this and rebuilding gradle's configuration you should be able to create aggregated Javadoc in specified directory by typing the following command via cli:
gradle aggregateJavadocs
Hope that helps somehow.
Helpful link: Android Gradle DSL

Get Android gradle plugin & checkstyle working together / command line usage

I'm evaluating the ability of the new gradle-based build system to reproduce our current ant-based build process and, as a gradle beginner, I failed to get checkstyle running with the android gradle plugin.
Environment:
gradle 1.6 running fine on a standard java project (checkstyle check target included)
up-to-date android SDK (22.0.1 with platform tools and build tools 17)
no eclipse, no android studio, only my lovely terminal
Symptom:
The target project is https://github.com/nibua-r/LigoTextDemo and I succeeded to build it using gradle but if I naively add apply plugin: checkstyle to my build.gradle:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.4.2'
}
}
apply plugin: 'android'
apply plugin: 'checkstyle'
android {
buildToolsVersion '17'
compileSdkVersion 15
testBuildType 'debug'
defaultConfig {
versionCode = 1
versionName = '1.0'
minSdkVersion 12
targetSdkVersion 15
}
buildTypes {
debug {
packageNameSuffix = '.debug'
}
}
}
then gradle check doesn't even complain on not finding the checkstyle.xml file (at the default config/checkstyle location) and returns:
:check UP-TO-DATE
BUILD SUCCESSFUL
What's needed:
First, I just need a running checkstyle target. Then, I need to automate checkstyle running as a dependency of the compilation (but lets get the chekstyle target up and running first).
Assumption:
This may be related to the fact that (from the [user guide][1]):
The Android plugin […] uses its own sourceSets
but I'm not enough gradle-efficient to understand what I'm missing there. Please, gradle Master, enlighten me with your valuable knowledge!
I got pmd, findbugs, and checkstyle working with Gradle 1.12 android plugin 0.12.+ using the following script:
apply plugin: 'checkstyle'
apply plugin: 'findbugs'
apply plugin: 'pmd'
check.dependsOn 'checkstyle', 'findbugs', 'pmd'
task checkstyle(type: Checkstyle) {
configFile file("${project.rootDir}/config/quality/checkstyle/checkstyle.xml")
source 'src'
include '**/*.java'
exclude '**/gen/**'
classpath = files()
}
task findbugs(type: FindBugs) {
ignoreFailures = true
effort = "max"
reportLevel = "high"
excludeFilter = new File("${project.rootDir}/config/quality/findbugs/findbugs-filter.xml")
classes = files("$project.buildDir/intermediates/classes/")
source 'src'
include '**/*.java'
exclude '**/gen/**'
reports {
xml {
destination "$project.buildDir/reports/findbugs/findbugs.xml"
xml.withMessages true
}
}
classpath = files()
}
task pmd(type: Pmd) {
ruleSetFiles = files("${project.rootDir}/config/quality/pmd/pmd-ruleset.xml")
ignoreFailures = true
ruleSets = ["basic", "braces", "strings"]
source 'src'
include '**/*.java'
exclude '**/gen/**'
reports {
xml.enabled = true
html.enabled = false
}
}
Running gradle build in command line will run all code quality plugins and generate xml reports in app/build/reports/ which are then ready to be viewed or parsed by CI tools.
Someone has a great answer to solve integrating PMD, findbugs and checkstyle with Gradle for Android.
Unfortunately, the only solution for now is based on ant :
http://sethrylan.org/2013/07/14/gradle-android-findbugs.html
I wish gradle will one day allow to do as much as maven for Android.
--- Update as of October 2013
With Gradle 1.8 and Android plugin for Gradle 0.6.+, you don't need this anymore. Android sourcesets and configurations are now compatible with the java plugin and all quality plugin work out of the box.
This includes pmd, findbugs, checkstyle and classycle.
--- Update
A configuration, largely inspired from the project mentioned above, is proposed in this open source project as well, plus other tools.
To get this to work with my Android project, I had to declare the task explicitly.
Here's what worked for me:
apply plugin: 'checkstyle'
task checkstyle(type: Checkstyle) {
source 'src'
include '**/*.java'
exclude '**/gen/**'
// empty classpath
classpath = files()
}
Be mindful that the Android plugin may choose to create a task of the same name in the future or work in conjunction with the checkstyle plugin in different ways.
You can try Android Check plugin (https://github.com/noveogroup/android-check):
Checkstyle
PMD
Configuration:
buildscript {
repositories { jcenter() }
dependencies {
...
classpath 'com.noveogroup.android:check:+'
...
}
}
apply plugin: 'com.noveogroup.android.check'
You can use hardcore configuration:
check {
abortOnError true
checkstyle { config hard() }
pmd { config hard() }
}
I found by digging on the web that the Android plugin depends on java-base and not java (i.e. the sourceSets management is specific) and the checkstyle plugin rely on java. As a consequence, some gradle upstream modification are needed to get the thing done. The gradle team is working on that, as seen on twitter:
#anzix Android source sets will be soon understood by the generic code quality plugins. Work on that has already started.— Gradle Build System (#Gradleware) May 26, 2013
Take a look at the Soter Gradle plugin to semlessly add support for Findbugs, Checkstyle and PMD to Android projects.

Categories

Resources