AndroidAnnotations Nothing Generated, Empty Activity - android
I am trying to create a project using AndroidAnnotations in Android Studio. When I build and run the project, everything seems to compile fine, yet I get nothing but a blank activity for the app. In addition, it does not appear that anything is generated by AndroidAnnotations.
I have added androidannotations-api-2.7.1.jar as a dependency for my project, and enabled annotation processing with the processor path the path to androidannotations-2.7.1.jar, which is in a separate folder from androidannotations-api-2.7.1.jar. I have checked store generated sources relative to module content root, and tried many different directories for the sources -- from generated, to gen/aa, to (currently) build/source/aa to match where it seems the generated files are created in Android Studio. Nothing has worked. I have changed the activity name in the manifest to Activity_, and set the configuration to launch this when the project is run.
The only other dependencies I have are android-support-v4 and ActionBarSherlock. I have tried with both of these disabled, to no result. I initially planned to use Roboguice in conjunction with AndroidAnnotations, but have disabled it for the time being to try to focus on this issue.
I am also using, or trying to use, Gradle. This is currently my build.gradle:
buildscript {
repositories {
maven { url 'http://repo1.maven.org/maven2' }
}
dependencies {
classpath 'com.android.tools.build:gradle:0.4'
}
}
apply plugin: 'android'
dependencies {
compile files('libs/android-support-v4.jar')
compile files('libs/actionbarsherlock-4.3.1.jar')
compile files('libs/androidannotations-api-2.7.1.jar')
}
android {
compileSdkVersion 17
buildToolsVersion "17.0.0"
defaultConfig {
minSdkVersion 7
targetSdkVersion 17
}
}
However, I haven't really figured out how Gradle works, so I mostly just manually added the dependencies as you would a normal project, then put the compile lines in Gradle so the project would compile properly. I know this is probably not the correct way to use it.
My activity and its layout are fairly standard, I just copied them from the official guide to get started with AndroidAnnotations.
UPDATE: So I just went back to Maven to test the build with that, and I noticed something strange. It seems that even with how I have it set up in Maven, nothing is generated. However, with the Maven build I can run the project without changing the activity name in the manifest to Activity_ and the project will compile and run correctly. This is very odd and seems like it could either further confuse the problem, or simplify it if it is indicative of something with Gradle as well.
This is similar to robotoaster's response, but it works in 0.4.1 and it places the generated java source files in a new directory (consistent with the other generated source folders), which allows Android Studio to see the source and stop complaining. It also works with more annotation processors. Just add your annotation processors to the "apt" configuration.
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.4.1'
}
}
apply plugin: 'android'
repositories {
mavenCentral()
}
ext.daggerVersion = '1.0.0';
ext.androidAnnotationsVersion = '2.7.1';
configurations {
apt
}
dependencies {
apt "com.googlecode.androidannotations:androidannotations:${androidAnnotationsVersion}"
compile "com.googlecode.androidannotations:androidannotations-api:${androidAnnotationsVersion}"
apt "com.squareup.dagger:dagger-compiler:${daggerVersion}"
compile "com.squareup.dagger:dagger:${daggerVersion}"
}
android {
compileSdkVersion 17
buildToolsVersion "17.0.0"
defaultConfig {
minSdkVersion 10
targetSdkVersion 17
}
}
android.applicationVariants.all { variant ->
aptOutput = file("${project.buildDir}/source/apt_generated/${variant.dirName}")
println "****************************"
println "variant: ${variant.name}"
println "manifest: ${variant.processResources.manifestFile}"
println "aptOutput: ${aptOutput}"
println "****************************"
variant.javaCompile.doFirst {
println "*** compile doFirst ${variant.name}"
aptOutput.mkdirs()
variant.javaCompile.options.compilerArgs += [
'-processorpath', configurations.apt.getAsPath(),
'-AandroidManifestFile=' + variant.processResources.manifestFile,
'-s', aptOutput
]
}
}
UPDATE: This still works to compile, but with Android Studio 0.1.1 you can no longer edit your project structure with the UI, so you can't tell AS to look at the new source folder. I'd like to add the folder to a sourceSet, but variants don't seem to actually have their own sourceSets so I'm not sure yet where to put it.
UPDATE 2: You can get Android Studio 0.1.1 to recognize the apt-generated source files by right-clicking on build/source/apt_generated/debug in the project browser and selecting Mark Directory As->Source Root
UPDATE 3: Since gradle plugin 0.5.5 the android.applicationVariants.each does not work anymore. Use android.applicationVariants.all instead. See the changelog at android.com:
access to the variants container don't force creating the task.
This means android.[application|Library|Test]Variants will be empty during the evaluation phase. To use it, use .all instead of .each
with the answers here and the help of +Hugo Visser who answered me on my Google+ Question i got this build.grade configuration, which allows gradew builds AND also adds the apt output path in Android Studio as source directorys.
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.5.+'
}
}
apply plugin: 'android'
repositories {
mavenCentral()
maven {
url 'https://oss.sonatype.org/content/repositories/snapshots/'
}
}
ext.androidAnnotationsVersion = '3.0-SNAPSHOT';
configurations {
apt
}
dependencies {
compile 'com.android.support:support-v4:13.0.+'
apt "org.androidannotations:androidannotations:${androidAnnotationsVersion}"
compile "org.androidannotations:androidannotations-api:${androidAnnotationsVersion}"
}
android {
compileSdkVersion 17
buildToolsVersion "17.0.0"
defaultConfig {
minSdkVersion 10
targetSdkVersion 17
}
}
def getSourceSetName(variant) {
return new File(variant.dirName).getName();
}
android.applicationVariants.all { variant ->
def aptOutputDir = project.file("build/source/apt")
def aptOutput = new File(aptOutputDir, variant.dirName)
println "****************************"
println "variant: ${variant.name}"
println "manifest: ${variant.processResources.manifestFile}"
println "aptOutput: ${aptOutput}"
println "****************************"
android.sourceSets[getSourceSetName(variant)].java.srcDirs+= aptOutput.getPath()
variant.javaCompile.options.compilerArgs += [
'-processorpath', configurations.apt.getAsPath(),
'-AandroidManifestFile=' + variant.processResources.manifestFile,
'-s', aptOutput
]
variant.javaCompile.source = variant.javaCompile.source.filter { p ->
return !p.getPath().startsWith(aptOutputDir.getPath())
}
variant.javaCompile.doFirst {
aptOutput.mkdirs()
}
}
UPDATE: updated for gradle android plugin 0.5.5; changed android.applicationVariants.each to android.applicationVariants.all
adding dependencies doesn't do anything. JavaCompile task has to be notified about annotation processor. It was possible to access JavaCompile task in version 0.3:
configurations {
compile
androidannotations.extendsFrom(compile)
}
dependencies {
compile 'org.androidannotations:androidannotations-api:3.0-SNAPSHOT'
androidannotations 'org.androidannotations:androidannotations:3.0-SNAPSHOT'
}
android.buildVariants.each {
variant ->
variant.javaCompile.options.compilerArgs += [
'-classpath', configurations.compile.asPath,
'-processorpath', configurations.androidannotations.asPath,
'-processor', 'org.androidannotations.AndroidAnnotationProcessor',
'-AandroidManifestFile=' + variant.processResources.manifestFile
]
}
For gradle plugin 0.4 onwards compile tasks have to be appended in different way. Thanks to Artiom # Android Project here is how entire build.gradle should look like
buildscript {
repositories {
maven { url 'http://repo1.maven.org/maven2' }
}
dependencies {
classpath 'com.android.tools.build:gradle:0.4'
}
}
apply plugin: 'android'
repositories {
mavenCentral()
maven {
url 'https://oss.sonatype.org/content/repositories/snapshots/'
}
}
configurations {
compile
androidannotations.extendsFrom(compile)
}
dependencies {
compile files('libs/android-support-v4.jar')
compile 'org.androidannotations:androidannotations-api:3.0-SNAPSHOT'
androidannotations 'org.androidannotations:androidannotations:3.0-SNAPSHOT'
}
android {
compileSdkVersion 17
buildToolsVersion "17.0.0"
defaultConfig {
minSdkVersion 7
targetSdkVersion 16
packageName "org.labaa.aa"
testPackageName "org.labaa.aa.test"
testInstrumentationRunner "org.labaa.aa.test.Runner"
}
}
afterEvaluate { project ->
android.applicationVariants.each { variant ->
variant.javaCompile.options.compilerArgs += [
'-classpath', configurations.compile.asPath,
'-processorpath', configurations.androidannotations.asPath,
'-processor', 'org.androidannotations.AndroidAnnotationProcessor',
'-AandroidManifestFile=' + variant.processResources.manifestFile
]
}
}
This won't update Android Studio dependencies. Add androidannotations-api manually. Run build from commandline
gradle installDebug
When compiling from Andoid Studio disable app launch otherwise launcher will complain about missing annotated activity.
The project now has up to date documentation for this case. A full example project also exists.
buildscript {
repositories {
mavenCentral()
}
dependencies {
// replace with the current version of the Android plugin
classpath 'com.android.tools.build:gradle:0.7.3+'
// the latest version of the android-apt plugin
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.2+'
}
}
apply plugin: 'android'
apply plugin: 'android-apt'
repositories {
mavenCentral()
}
android {
compileSdkVersion 19
buildToolsVersion "19.0.1"
defaultConfig {
minSdkVersion 15
targetSdkVersion 19
versionCode 1
versionName "1.0"
}
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
}
apt {
arguments {
androidManifestFile variant.processResources.manifestFile
// If you're using Android NBS flavors you should use the following line instead of hard-coded packageName
//resourcePackageName android.defaultConfig.packageName
resourcePackageName "com.example.your.package.name"
// You can set optional annotation processing options here, like these commented options:
// logLevel 'INFO'
// logFile '/var/log/aa.log'
}
}
dependencies {
apt "org.androidannotations:androidannotations:3.0+"
compile "org.androidannotations:androidannotations-api:3.0+"
}
this is an update to the answer that does the following things:
works with Android Studio 0.1.9
removes syntax errors from IDE (even on rebuilds)
uses androidannotations without dagger
In order to achieve this I copy the output to build/source/r witch will remain marked as source during rebuilds.
import groovy.io.FileType
buildscript {
}
apply plugin: 'android'
repositories {
mavenCentral()
}
ext.androidAnnotationsVersion = '2.7.1';
configurations {
apt
}
dependencies {
apt "com.googlecode.androidannotations:androidannotations:${androidAnnotationsVersion}"
compile "com.googlecode.androidannotations:androidannotations-api:${androidAnnotationsVersion}"
}
android {
compileSdkVersion 17
buildToolsVersion "17.0.0"
defaultConfig {
minSdkVersion 10
targetSdkVersion 16
}
}
android.applicationVariants.each { variant ->
aptOutput = file("${project.buildDir}/source/r/${variant.dirName}")
println "****************************"
println "variant: ${variant.name}"
println "manifest: ${variant.processResources.manifestFile}"
println "aptOutput: ${aptOutput}"
println "****************************"
variant.javaCompile.doFirst {
println "*** compile doFirst ${variant.name}"
aptOutput.mkdirs()
aptOutput.eachFileRecurse FileType.FILES, {
if (it.name.equals('R.java')) {
return
}
it.delete()
}
variant.javaCompile.options.compilerArgs += [
'-processorpath', configurations.apt.getAsPath(),
'-AandroidManifestFile=' + variant.processResources.manifestFile,
'-s', aptOutput
]
}
}
Still pretty hacky improvement suggestions are welcomed
EDIT the android-apt way
Recently a package called android-apt https://bitbucket.org/hvisser/android-apt/overview was release that makes things a lot easier (version 1.1 has the support android annotations needs)
Simply update your build.gradle like so:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath "com.neenbedankt.gradle.plugins:android-apt:1.1"
}
}
apply plugin: 'android-apt'
apt {
arguments {
androidManifestFile variant.processResources.manifestFile
}
}
dependencies {
apt 'com.googlecode.androidannotations:androidannotations:2.7.+'
}
A big thank you goes to hvisser the creator of android-apt
One possible problem is the R class is not found. Android Studio doesn't place the R.java into the gen directory by default like eclipse. The solution is to go into Project Settings -> Facets -> Select the Android facet for your project -> Compiler tab, and change the "R.java and Manifest.java files" from "Run process-resources Maven task before Make" to "Generated by IDE".
Related
Android: Cannot include https://github.com/wealdtech/hawk as a module
I am trying out Hawk authentication by https://github.com/wealdtech/hawk. I would like to include this library by source in an empty project so that I can experiment with the apis. I do not want to use a jar or gradle dependency. I import the project as a module and I run into this error: Error:(2, 0) Gradle DSL method not found: 'compile()' Possible causes:<ul><li>The project 'HawkTest' may be using a version of Gradle that does not contain the method. Open Gradle wrapper file</li><li>The build file may be missing a Gradle plugin. Apply Gradle plugin</li> I tried solutions from these links but I could not derive any information that could help resolve this issue: Android gradle build Error:(9, 0) Gradle DSL method not found: 'compile()'. Android gradle build Error:(9, 0) Gradle DSL method not found: 'compile()'. I have spent many hours on this problem but do not seem anywhere near a solution. Any direction or a solution would be greatly appreciated. This my top-level build file: // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { jcenter() } dependencies { classpath 'com.android.tools.build:gradle:2.1.2' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { jcenter() } } task clean(type: Delete) { delete rootProject.buildDir } The app level file: apply plugin: 'com.android.application' android { compileSdkVersion 23 buildToolsVersion "23.0.3" defaultConfig { applicationId "com.test.android.hawktest" minSdkVersion 16 targetSdkVersion 23 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } } dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.4.0' } The Hawk module's gradle file: dependencies { compile 'com.wealdtech:wealdtech-core:2.0.0' compile 'com.wealdtech:wealdtech-configuration:2.0.0' compile 'com.google.guava:guava:17.0' } uploadArchives { repositories { mavenDeployer { pom.project { pom.artifactId = 'hawk-core' name 'Hawk Core' description 'Java implementation of Hawk protocol - core' } } } } And my directory structure:
hawk top level build.gradle contains all subproject configuration (check https://github.com/wealdtech/hawk/blob/develop/build.gradle) For the whole process, from your project root directory : git clone git#github.com:wealdtech/hawk.git In your settings.gradle, this will configure the gradle modules : include ':app',':hawk-core', ':hawk-server-jersey', ':hawk-client-jersey' project(':hawk-core').projectDir = new File('hawk/hawk-core') project(':hawk-server-jersey').projectDir = new File('hawk/hawk-server-jersey') project(':hawk-client-jersey').projectDir = new File('hawk/hawk-client-jersey') Then edit your top level build.gradle to specify the configuration for the Java project. Add the following : configure(subprojects.findAll {it.name.startsWith('hawk')}) { apply plugin: 'java' apply plugin: 'maven' apply plugin: 'idea' apply plugin: 'signing' repositories { mavenCentral() mavenLocal() } dependencies { testCompile 'org.testng:testng:6.8' } task copyLibs (type: Copy) { into "$buildDir/output/libs" from configurations.testRuntime } task testJar (type: Jar) { classifier = 'tests' from sourceSets.test.output } task javadocJar(type: Jar, dependsOn: javadoc) { classifier = 'javadoc' from 'build/docs/javadoc' } task sourcesJar(type: Jar) { classifier = 'sources' from sourceSets.main.allSource } artifacts { archives jar archives javadocJar archives sourcesJar } } You cant add Java plugin (apply plugin: 'java') for your Android project . If you do so, you will have this error : The 'java' plugin has been applied, but it is not compatible with the Android plugins.. This is why I use the configure(subprojects.findAll and perform a filter on hawk modules. I've copied the remaining configuration from https://github.com/wealdtech/hawk/blob/develop/build.gradle
'dependencies' cannot be applied to '(groovy.lang.Closure)'
I am unable to fix this error: dependencies cannot be applied to '(groovy.lang.Closure) This is my gradle file: buildscript { repositories { maven { url 'http://download.crashlytics.com/maven' } } dependencies { classpath 'com.crashlytics.tools.gradle:crashlytics-gradle:1.+' } } apply plugin: 'android' apply plugin: 'crashlytics' repositories { maven { url 'http://download.crashlytics.com/maven' } } dependencies { compile fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar') compile fileTree(dir: 'libs', include: '*.jar') compile project(':FRNDzTER_core') compile project(':cropper') compile project(':stickyListHeaders') compile "com.nostra13.universalimageloader:universal-image-loader:${rootProject.universalImageLoaderVersion}" compile "com.google.android.gms:play- services:${rootProject.googlePlayServicesVersion}" compile "de.keyboardsurfer.android.widget:crouton:${rootProject.croutonVersion}" compile "com.nineoldandroids:library:${rootProject.nineoldandroidsVersion}" compile 'com.github.chrisbanes.actionbarpulltorefresh:library:+' compile 'com.crashlytics.android:crashlytics:1.+' } android{ compileSdkVersion rootProject.compileSdkVersion buildToolsVersion rootProject.buildToolsVersion defaultConfig { minSdkVersion rootProject.minSdkVersion targetSdkVersion rootProject.targetSdkVersion versionCode rootProject.versionCode versionName rootProject.versionName } buildTypes { release { debuggable rootProject.prodDebug proguardFile 'proguard.cfg' } } dependencies { } packagingOptions { exclude 'META-INF/LICENSE.txt' exclude 'META-INF/NOTICE.txt' } lintOptions { abortOnError false } }
You can go to Preferences and select "use default gradle wrapper" then rebuild the project. It worked well for me:
Go to Windows File -> Settings -> Build, Execution, Deployment -> Build Tools -> Gradle Mac Preference -> Build, Execution, Deployment -> Build Tools -> Gradle and select Use default gradle wrapper
Based on what Android Studio generates, you need to have a top-level project file build.gradle, and another for your app build.gradle. Top-level: // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { jcenter() maven { url 'http://download.crashlytics.com/maven' } } dependencies { classpath 'com.android.tools.build:gradle:1.1.0' classpath 'com.crashlytics.tools.gradle:crashlytics-gradle:1.+' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { jcenter() maven { url 'http://download.crashlytics.com/maven' } } } Application level: apply plugin: 'com.android.application' apply plugin: 'crashlytics' android{ compileSdkVersion rootProject.compileSdkVersion buildToolsVersion rootProject.buildToolsVersion defaultConfig { minSdkVersion rootProject.minSdkVersion targetSdkVersion rootProject.targetSdkVersion versionCode rootProject.versionCode versionName rootProject.versionName } buildTypes { release { debuggable rootProject.prodDebug proguardFile 'proguard.cfg' } } packagingOptions { exclude 'META-INF/LICENSE.txt' exclude 'META-INF/NOTICE.txt' } lintOptions { abortOnError false } } ` dependencies { compile fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar') compile fileTree(dir: 'libs', include: '*.jar') compile project(':FRNDzTER_core') compile project(':cropper') compile project(':stickyListHeaders') compile "com.nostra13.universalimageloader:universal-image- l loader:${rootProject.universalImageLoaderVersion}" compile "com.google.android.gms:play- services:${rootProject.googlePlayServicesVersion}" compile " "de.keyboardsurfer.android.widget:crouton:${rootProject.croutonVersion}" compile "com.nineoldandroids:library:${rootProject.nineoldandroidsVersion}" compile 'com.github.chrisbanes.actionbarpulltorefresh:library:+' compile 'com.crashlytics.android:crashlytics:1.+' } But even without all that, your problem is that you have a dependencies within your android plugin config. android { dependencies { } } remove that empty dependencies block. EDIT: I also started getting this error with the latest Android Studio, all I had to do was add a newer version of the Gradle plugin, and compileSdkVersion 22. buildscript { repositories { jcenter() mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:1.3.0' classpath 'com.neenbedankt.gradle.plugins:android-apt:1.4' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { jcenter() mavenCentral() } }
If you already are using the "default gradle wrapper" and it doesn't help: In Menu click: File -> Invalidate Caches / Restart... If it also doesn't help try in 2 steps: 1) Delete ".gradle" folder (and "build" folder if you have it already) 2) In Menu click: File -> Invalidate Caches / Restart... After restarting the warning should disappear. (For me it worked and for Android Studio and for IntelliJ Idea)
My problem is that the whole build.setting file were occupied with cannot be applied to '(groovy.lang.Closure)' warning messages instead of happening on any particular variable. I have tried all solutions provided by others but none of them works for me. I ended out doing these steps then it works like a charm. If you are encountering the same issue then give it a try. Open and edit file: yourproject/gradle/wrapper/gradle-wrapper.properties. Edit content to update the gradle distribution version as shown in the image below then save. Delete this folder: yourproject/.gradle. Click Sync project with gradle files, then you are good to go.
I went into the preferences to try one of the other answers when I noticed a warning that my gradle home directory was wrong. So I opened up the file browser and chose the newer gradle version, and all the errors went away. Image shown below.
I bet you the problem is totally unrelated to the piece of code that is giving you warnings, most likely it's your proguard file. I had the following in my code and got the same warning: buildTypes { release { runProguard false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' } } By commenting out runProguard false, all of my problems go away, go figure :)
I have same problem in android studio 2.2,it work for me: original: android { ... } dependencies { ... } move dependencies in android: android { ... dependencies { ... } }
I solved the problem in Android Studio by Invalidating the cache and restart. File-> Invalidate Caches / Restart..
I ran into a similar problem to this in IntelliJ for a Kotlin project. It looks like the issue was that in my project, even though it was set to use JDK 8, the language and API versions somehow got set to 1.3. See Project Preferences > Facets. In my case, I ticked "use project settings," but manually setting them per facet may work as well.
Close the project (File / Close project), Select “Open an existing Android Studio project” on the start menu and select the folder that contains your Android project. This work for me.
Gradle files can be made explicit in several places to avoid such errors. E.g. Change configurations { to project.configurations { or task { description 'foo' to task { setDescription 'foo'
To fix the issue simply close the project, then select “Open an existing Android Studio project” on the start menu and select the folder that contains your Android project. Beware, select the folder, not the .iml project file.
Cut and then paste the "buildTypes" at the same place in "android" section and Re-Sync (refresh) Project
For people with M1 Intellij IDEA just add in build.gradle(:app) //noinspection GroovyAssignabilityCheck buildFeatures { viewBinding }
I fixed this issue with gradle 2.10. Download it here : http://gradle.org/gradle-download/ And set your local gradle distribution like this :
How to configure dagger + gradle
I have a project and migrating to gradle dependency, but I find myself with an issue trying to setup dagger with gradle, the first time I compile it work perfectly (or if I clean) but if I try it twice then it gives me error like: Error:(13, 14) error: duplicate class: com.myapp.android.application.InjectingApplication$InjectingApplicationModule$$ModuleAdapter I try using android-apt plugin and configured as in the documentation but I still get the same error (https://bitbucket.org/hvisser/android-apt/overview) I also try using provided dependency instead like in this tutorial (https://github.com/frankdu/android-gradle-dagger-tutorial) of compile but no luck so far. Do you have any ideas how to configure dagger and gradle? EDIT My build.gradle looks like this apply plugin: 'android' apply plugin: 'android-apt' android { compileSdkVersion 19 buildToolsVersion "19.0.2" defaultConfig { minSdkVersion 9 targetSdkVersion 19 packageName "com.myapp.android" } buildTypes { release { runProguard false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt' } } } dependencies { compile project(':volley') apt 'com.squareup.dagger:dagger-compiler:1.2.0' compile 'com.squareup.dagger:dagger:1.2.0' } And my top level build.gradle look like this // Top-level build file where you can add configuration options common to all sub-projects/modules. buildscript { repositories { mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:0.9.+' classpath 'com.neenbedankt.gradle.plugins:android-apt:1.2' } } allprojects { repositories { mavenCentral() } } EDIT#2: I tried with provided again as #Marco suggested no luck, I don't know if there is a library or a version of gradle that could be causing this problem, I'm currently using 1.10. On the bright side I did find a way to make it work, but I would love to do it by just adding the provided statement. The way I did it is the old way: Define apt configuration configurations { apt } add Dagger compiler lib apt 'com.squareup.dagger:dagger-compiler:1.2.0' And implement the this hook to applicationVariant which as far as I know android-apt does something similar. Does this make sense? why? def getSourceSetName(variant) { return new File(variant.dirName).getName(); } android.applicationVariants.each { variant -> def aptOutputDir = project.file("build/source/apt") def aptOutput = new File(aptOutputDir, variant.dirName) android.sourceSets[getSourceSetName(variant)].java.srcDirs+= aptOutput.getPath() variant.javaCompile.options.compilerArgs += [ '-processorpath', configurations.apt.getAsPath(), '-s', aptOutput ] variant.javaCompile.source = variant.javaCompile.source.filter { p -> return !p.getPath().startsWith(aptOutputDir.getPath()) } variant.javaCompile.doFirst { aptOutput.mkdirs() } }
I am using dagger in this sample Volley Examples. I'm not experiencing any problems with dagger and I'm including the compiler using: provided 'com.squareup.dagger:dagger-compiler:1.2.1'
It is work for me. Step 1: Add this code to you build.gradle provided 'com.squareup.dagger:dagger-compiler:1.2.2' Step 2: Add source code folder app/gen to you project. So you can add this code to you app/build.gradle (src/main/java is you project core code folder) sourceSets.main { java.srcDirs = ['src/main/java', 'gen'] }
Update Gradle plugin to (root/gradle) classpath 'com.android.tools.build:gradle:2.2.0' app/gradle compile 'com.google.dagger:dagger:2.4' annotationProcessor 'com.google.dagger:dagger-compiler:2.4'
What is the correct way to specify an Android library project to include its dependencies
In Android Studio I'm trying to compile an Android application module which uses an Android library. The library includes a jar file for Bugsense (included automatically by gradle). Although the library module compiles correctly, the application module fails because it is looking for the Bugsense jar file that is used within the library module. I do have a workaround which allows the project to compile. By also including the Bugsense dependency in the project everything works. My question is: How do I make the project compile without duplicating the Bugsense dependency? Here is my build.gradle file for the library project. buildscript { repositories { mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:0.6.+' } } apply plugin: 'android-library' repositories { mavenCentral() maven { url 'http://www.bugsense.com/gradle/' } } android { compileSdkVersion 15 buildToolsVersion "19.0.0" defaultConfig { minSdkVersion 15 targetSdkVersion 15 } } dependencies { compile 'com.bugsense.trace:bugsense:3.6' } The library project is called "util" Following is the android section of the build.gradle for the application android { compileSdkVersion 15 buildToolsVersion '19.0.0' defaultConfig { minSdkVersion 15 targetSdkVersion 15 } dependencies { compile project(':util') } } When I compile this I get the following error: * What went wrong: A problem occurred configuring project ':br'. > Failed to notify project evaluation listener. > Could not resolve all dependencies for configuration ':br:_DebugCompile'. > Could not find com.bugsense.trace:bugsense:3.6. Required by: dss:br:unspecified > dss:util:unspecified I can make the compile work by adding Bugsense to the repositories section of the build.gradle file for the application. Following is the code I added to the build.gradle file for the application project. repositories { mavenCentral() maven { url 'http://www.bugsense.com/gradle/' } } Remember, the above code is in the build.gradle for the application project AND the library. How do I avoid adding the Bugsense dependency to both the application and library projects? UPDATES: I'm using Gradle 1.8 I'm compiling from the command line with "gradle clean assembleDebug" The following is the complete build.gradle file for the application project: buildscript { repositories { mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:0.6.+' } } apply plugin: 'android' repositories { mavenCentral() //maven { url 'http://www.bugsense.com/gradle/' } } android { compileSdkVersion 15 buildToolsVersion '19.0.0' defaultConfig { minSdkVersion 15 targetSdkVersion 15 testPackageName "com.myapp.test" } dependencies { compile project(':common') compile project(':util') } } dependencies { instrumentTestCompile 'com.jayway.android.robotium:robotium-solo:4.3' instrumentTestCompile 'com.squareup:fest-android:1.0.+' instrumentTestCompile 'com.squareup.spoon:spoon-client:1.0.+' instrumentTestCompile 'com.google.guava:guava:15.0' } configurations { spoon } dependencies { spoon 'com.squareup.spoon:spoon-runner:1.0.5' }
It's the expected behavior. Only the repository declarations for the project whose configuration is currently resolved are taken into account, even when transitive dependencies are involved. Typically, repositories are declared inside the root project's allprojects { .. } or subprojects { ... } block, in which case this problem can never occur. PS: dependencies { .. } needs to go outside the android { ... } block.
Building APK with Gradle outside IDE (migrating from Ant)
I have been using this tutorial to educate myself on how to build APK outside Eclipse by just using command line (and Ant) - http://www.androidengineer.com/2010/06/using-ant-to-automate-building-android.html Now that build system will be shifting toward Gradle I would like to have similar advanced tutorial for reference. Most of the tutorials out there (like this one)deal just with basic stuff but I would like to know how to perform some "advanced" things like automatically replacing values in code during build (so that I can have multiple variants of APK).
Standard examples provided by Google are here http://tools.android.com/tech-docs/new-build-system/gradle-samples-0.4.2.zip?attredirects=0&d=1 For automatically changing values in code use BuildConfig class. Examples are in the link above. Variants are explained here http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants UPDATE as this example gets bit stale here is pasetbin to newer version http://pastebin.com/FmcCZwA5 main difference is Robolectric support provided by plugin, and support library fetched from SDK internal repo Older version Less basic example with Robolectric and AndroidAnnotations Use nexus buildscript { repositories { mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:0.4' } } apply plugin: 'android' repositories { mavenCentral() maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' } } use AndroidAnnotation processor, Robolectric local tests and Jackson configurations { compile testLocalCompile.extendsFrom(compile) androidannotations.extendsFrom(compile) } dependencies { compile files('libs/android-support-v4.jar') compile 'org.androidannotations:androidannotations-api:3.0-SNAPSHOT' compile 'com.github.japgolly.android:svg-android:2.0.3' compile 'org.codehaus.jackson:jackson-mapper-asl:1.9.12' testLocalCompile 'junit:junit:4.8.2' testLocalCompile 'org.robolectric:robolectric:2.2-SNAPSHOT' testLocalCompile 'com.google.android:android:4.0.1.2' testLocalCompile 'com.google.android:support-v4:r6' testLocalCompile 'org.roboguice:roboguice:2.0' androidannotations 'org.androidannotations:androidannotations:3.0-SNAPSHOT' } android { compileSdkVersion 17 buildToolsVersion "17.0.0" Configure standard instrumentation tests defaultConfig { minSdkVersion 7 targetSdkVersion 16 testPackageName "com.mypackage.myapp.test" testInstrumentationRunner "com.maypackage.myapp.test.Runner" } } Invoke AndroidAnnotations processor on all variants afterEvaluate { project -> android.applicationVariants.each { variant -> variant.javaCompile.options.compilerArgs += [ '-classpath', configurations.compile.asPath, '-processorpath', configurations.androidannotations.asPath, '-processor', 'org.androidannotations.AndroidAnnotationProcessor', '-AandroidManifestFile=' + variant.processResources.manifestFile ] } } Define sourcesets for Robolectric local tests sourceSets { testLocal { java.srcDir file('src/test/java') resources.srcDir file('src/test/resources') } } Local Robolectric tests task task localTest(type: Test, dependsOn: assemble) { testClassesDir = sourceSets.testLocal.output.classesDir android.sourceSets.main.java.srcDirs.each { dir -> def buildDir = dir.getAbsolutePath().split('/') buildDir = (buildDir[0..(buildDir.length - 4)] + ['build', 'classes', 'debug']).join('/') sourceSets.testLocal.compileClasspath += files(buildDir) sourceSets.testLocal.runtimeClasspath += files(buildDir) } classpath = sourceSets.testLocal.runtimeClasspath } Run Robolectric in debug mode localTest.doFirst { jvmArgs '-Xdebug', '-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005' }