In my android application I need to generate source code and use it in the app.
For that I created task genSources (using tutorials) for source generation. It works correctly if run it separately.
In my case I need to run source code generation automatically.
From tutorial I found out the following command:
compileJava.dependsOn(genSources)
but that is unknown command for the 
apply plugin: 'com.android.library'
gradle throws following exception:Error:(35, 0) Could not find property 'compileJava' on project ':data'.
Looks like it can be used with apply plugin: 'Java'
but I cannot use these 2 plugins together
How can I solve this issue and generate needed source code before compilation?
build.gradle
apply plugin: 'com.android.library'
configurations {pmd}
android {
    compileSdkVersion 21
    buildToolsVersion "21.1.2"
    defaultConfig {
        minSdkVersion 19
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
buildscript {
    repositories {
        maven {
            url "http://repo1.maven.org/maven2/"
        }
    }
    dependencies {
        classpath group: 'net.sourceforge.fmpp', name: 'fmpp', version: '0.9.14'
    }
    ant.taskdef(name: 'fmpp', classname:'fmpp.tools.AntTask', classpath: buildscript.configurations.classpath.asPath)
}
task genSources << {
    println "Generating sources...."
    ant.fmpp configuration:"src/main/resources/codegen/config.fmpp",
            sourceRoot:"src/main/resources/codegen/templates",
            outputRoot:"target/generated-sources/main/java";
}
compileJava.dependsOn(genSources)
sourceSets {
    main {
        java {
            srcDir 'target/generated-sources/main/java'
        }
    }
}
dependencies {
    ...
}
UPDATED
I was found some solution which at least not throw exception
gradle.projectsEvaluated {
    compileJava.dependsOn(genSources)
}
Then I execute gradle build but nothing happens
With gradle 2.2+ this should work:
tasks.withType(JavaCompile) {
    compileTask -> compileTask.dependsOn genSources
}
If you also want it to happen when you evaluate (e.g. when syncing your project with gradle in android studio) you can do it like this:
gradle.projectsEvaluated {
    preBuild.dependsOn genSources
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With