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'
Related
I imported the sample app in Android Studio under the location section. I then proceeded to update most of the dependancies. I then attempted to add Firebase and that's when things went south. The module build.gradle is below.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.2'
}
}
apply plugin: 'com.android.application'
repositories {
jcenter()
}
dependencies {
compile 'com.google.android.gms:play-services-location:10.0.1'
compile 'com.google.android.gms:play-services-maps:10.0.1'
compile 'com.github.bumptech.glide:glide:3.6.1'
compile 'com.google.maps.android:android-maps-utils:0.4.4'
compile 'com.android.support:appcompat-v7:25.0.1'
compile 'com.android.support:recyclerview-v7:25.0.1'
compile 'com.android.support:design:25.0.1'
compile 'com.google.android.gms:play-services-wearable:10.0.1'
compile 'com.android.support:support-v13:25.0.1'
compile project(':Shared')
wearApp project(':Wearable')
}
// The sample build uses multiple directories to
// keep boilerplate and common code separate from
// the main sample code.
List<String> dirs = [
'main', // main sample code; look here for the interesting stuff.
'common', // components that are reused by multiple samples
'template'] // boilerplate code that is generated by the sample template process
android {
compileSdkVersion 25
buildToolsVersion '24.0.2'
defaultConfig {
minSdkVersion 18
targetSdkVersion 25
versionCode 1
versionName "1.0"
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
sourceSets {
main {
dirs.each { dir ->
java.srcDirs "src/${dir}/java"
res.srcDirs "src/${dir}/res"
}
}
androidTest.setRoot('tests')
androidTest.java.srcDirs = ['tests/src']
}
productFlavors {
}
}
apply plugin: 'com.google.gms.google-services'
The root build.gradle is below.
buildscript {
// ...
dependencies {
// ...
classpath 'com.google.gms:google-services:3.0.0'
}
}
And the error I receive is :
Error:Could not find com.google.gms:google-services:3.0.0.
Searched in the following locations:
file:/C:/Android/Android Studio/gradle/m2repository/com/google/gms/google-services/3.0.0/google-services-3.0.0.pom
file:/C:/Android/Android Studio/gradle/m2repository/com/google/gms/google-services/3.0.0/google-services-3.0.0.jar
Required by:
:ToledoZoo:unspecified
Using the latest SDK, and all. Added the google.json file to the app directory as well. I am sure it is something small I am missing, but yet... still missing it!
The module build.gradle is below
app/ is a module, and the buildscript block should not be within that.
The app build.gradle is below.
If by this, you mean build.gradle in the root of the project, then it is that file where you add the classpath of the play services.
Refer. https://firebase.google.com/docs/android/setup#add_the_sdk
Note, when the documentation says
buildscript {
// ...
dependencies {
// ...
classpath 'com.google.gms:google-services:3.0.0'
}
You do not literally copy the // ... pieces. It means "leave what is there already".
If you have a single module Gradle project, then that might make sense looking at your question, and so you need to have
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.2'
classpath 'com.google.gms:google-services:3.0.0'
}
}
apply plugin: 'com.android.application'
// rest of gradle file
I'm not a Gradle expert. That said, the layout of your build.gradle files is unconventional. Typically, in the module file, the dependencies block is after the android block. Examples of build files are in the Firebase sample project. Take a look at this sample project build file and this sample module build file.
i have a hello world full screen android studio 1.5.1 app that i added a gradle/eclipse-mars subproject to. no other files were modified except for adding include ':javalib' to settings.gradle. adding a project lib dependency:
project(':app') {
dependencies {
compile project(':javalib') // line 23
}
}
to the root build build file and running gradle from the command line , gets:
Where:
Build file 'D:\AndroidStudioProjects\AndroidMain\build.gradle' line: 23
What went wrong:
A problem occurred evaluating root project 'AndroidMain'.
Could not find method compile() for arguments [project ':javalib'] on org.grad
le.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler_Decorated#46
3ca82f.
adding the java plugin to the root build file did not help.
i don't think it's in the wrong place.
both the root project and the added subproject have the gradle wrapper.
any pointers will be appreciated.
thanks
edit: for clarification, the root build file is:
// 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:1.5.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
task hello << { task -> println "I'm $task.project.name" }
}
project(':app') {
dependencies {
//compile project(':javalib') // causes problems
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
and the app build file is:
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.1"
defaultConfig {
applicationId "acme.androidmain"
minSdkVersion 22
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'])
//compile project(':javalib') // use :javalib:jar?
//testCompile project(':javalib')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:support-v4:23.1.1'
}
edit: the whole purpose of this exercise is to get core java code into an android project. currently the core code is a standalone gradle/eclispe project. i have a batch in the android project that does a gradle -p standaloneprojectdir/ jar and copied the jar into libs/.
i just though there would be an easier way other than to publish the jar and get it from a repository since this all done on my pc.
it would be nice to have all the code live and just do a build :(
edit: as per RaGe's suggestion, here is a virgin android studio project and a virgin gradle/eclipse project. no editing has been done to these files. you mission should you choose to accept it is to get the android app to easily access the java project classes (i.e. new Library(); in MainActivity.onCreate() will compile and run). i don't care where the java project lives. ideally, both sources would be live in both ide's.
atempting this fails also. says: > Could not find :virginjavaproject, but directory does exist.
edit: what actually worked was RaGe's pull request to the virgin android project.
You already have
compile project(':javalib')
in your :app project, you don't have to also inject the dependency from your root build.gradle. If you still want to do it from the root build.gradle, the correct way to do it is:
configure(':app') {
dependencies {
compile project(':javalib') // causes problems - NOT ANYMORE!
}
}
the virgin android studio head is what worked.
We have 2 files named "build.gradle".
make sure you have copied your "compile code" in the build.gradle file that is inside "app" folder
As stated by #peter-niederwieser:
The build script is mixing up buildscript dependencies (i.e. dependencies of the build itself; typically this means Gradle plugins) with regular dependencies (i.e. dependencies of the code to be compiled/run). The latter need to go into dependencies { ... }, not into buildscript { dependencies { ... } }. Everything but the classpath dependencies are regular dependencies.
Also have a look at this: Could not find method compile() for arguments Gradle.
Simply paste this on build.gradle(Project:"Your prject name")
// 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
}
I had this problem but with my own library. The way to correctly compile was:
compile project(path: ':MyLib')
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 :
So I have created an Android library and successfully compiled it into a .aar file. I called this aar file: "projectx-sdk-1.0.0.aar". Now I want my new project to depend on this aar so what I have done is follow this post.
But the post confuses me since I do not get the desired result:
The package name of the aar is : com.projectx.photosdk and the module inside is called sdk
Here is my current project structure:
|-SuperAwesomeApp
|--.idea
|--gradle
|--App
|---aars
|----projectx-sdk-1.0.0.aar
|---build
|---jars
|---src
|---build.gradle
And here is my Gradle build file:
apply plugin: 'android'
buildscript {
repositories {
mavenCentral()
flatDir {
dirs 'aars'
}
}
}
android {
compileSdkVersion 19
buildToolsVersion "19.0.1"
defaultConfig {
minSdkVersion 11
targetSdkVersion 19
versionCode 1
versionName "1.0"
}
buildTypes {
release {
runProguard false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
}
dependencies {
compile 'com.android.support:gridlayout-v7:19.0.1'
compile 'com.android.support:support-v4:19.0.1'
compile 'com.android.support:appcompat-v7:19.0.1'
compile 'com.projectx.photosdk:sdk:1.0.0#aar'
// compile files( 'aars/sdk-1.0.0.aar' ) // Does not work either
}
EDIT
The errors I am getting:
Failed to refresh Gradle project 'SuperAwesomeApp'
Could not find com.projectx.photosdk:sdk:1.0.0.
Required by:
SuperAwesomeApp:App:unspecified
You put your flatDir block in the wrong repostories block. The repositories block inside buildscript tells Gradle where to find the Android-Gradle plugin, but not the rest of the dependencies. You need to have another top-level repositories block like this:
repositories {
mavenCentral()
flatDir {
dirs 'aars'
}
}
I tested this and it works okay on my setup.
With recent versions of Android Studio, tested with 1.3, to use local .AAR file and not one fetched from maven/jcenter repository, just go to File > New > New module and choose Import .JAR/.AAR Package.
What you will end up with is a new module in your project that contains very simple build.gradle file that looks more or less like this:
configurations.create("default")
artifacts.add("default", file('this-is-yours-package-in-aar-format.aar'))
Of course, other projects have to reference this new module with regular compile project directive. So in a project that uses this new module which is simple a local .aar file has this in it's build.gradle
[...]
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.0'
compile 'com.android.support:design:23.1.0'
[...]
compile project(':name-of-module-created-via-new-module-option-described-above')
}
[...]
In Android Studio 3.1.3 with gradle 3.0.1.
Simply adding implementation fileTree(dir: 'libs', include: ['*.aar']) or implementation files('libs/app-release.aar') without any other flatdir works.
These days (over 1 year after this question) with Android Studio >1.0, local dependency does work properly:
The android sdk looks for dependencies in a default local repo of: $ANDROID_HOME/extras/android/m2repository/
In a local library project you can publish the aar to this directory. Here's a snippet that can be added to your module's build.gradle file (ex: sdk/build.gradle)
apply plugin: 'maven'
uploadArchives {
repositories {
mavenDeployer {
repository(url: "file://localhost" + System.getenv("ANDROID_HOME")
+ "/extras/android/m2repository/")
pom.version = '1.0-SNAPSHOT'
pom.groupId = 'your.package'
pom.artifactId = 'sdk-name'
}
}
}
some reference gradle docs http://gradle.org/docs/current/userguide/artifact_management.html
In your library project, run ./gradlew uploadArchives to publish the aar to that directory
In the application project you want to use the library in, add the dependency to your project/app/build.gradle. compile 'your.package:sdk-name:1.0-SNAPSHOT'
For local dependency, the next gradle build should find the previously deployed archive and that's it!
In my case, I use the above for local dev, but also have a Bamboo continuous integration server for the Library that publishes each build to a shared Nexus artifact repository. The full library code to deploy the artifact then becomes:
uploadArchives {
repositories {
mavenDeployer {
if (System.getenv("BAMBOO_BUILDNUMBER") != null) {
// Deploy to shared repository
repository(url: "http://internal-nexus.url/path/") {
authentication(userName: "user", password: "****")
}
pom.version = System.getenv("BAMBOO_BUILDNUMBER")
} else {
// Deploy to local Android sdk m2repository
repository(url: "file://localhost" + System.getenv("ANDROID_HOME")
+ "/extras/android/m2repository/")
pom.version = '1.0-SNAPSHOT'
}
pom.groupId = 'your.package'
pom.artifactId = 'sdk-name'
}
}
}
In order to tell applications to download from my internal Nexus repository, I added the internal Nexus maven repository just above jcenter() in both "repositories" blocks in the project/build.gradle
repositories {
maven {
url "http://internal-nexus.url/path/"
}
jcenter()
}
And application dependency then looks like compile 'your.package:sdk-name:45' When I update the 45 version to 46 is when my project will grab the new artifact from the Nexus server.
With the newest Gradle version there is now a slightly updated way of doing what Stan suggested (see maving publishing)
apply plugin: 'maven-publish'
publishing {
publications {
aar(MavenPublication) {
groupId 'org.your-group-id'
artifactId 'your-artifact-id'
version 'x.x.x'
// Tell maven to prepare the generated "*.aar" file for publishing
artifact("$buildDir/outputs/aar/${project.getName()}-release.aar")
}
}
repositories {
maven {
url("file:" + System.getenv("HOME") + "/.m2/repository")
}
}
}
It seems adding .aar files as local dependency is not yet supported(Planned to be supported in 0.5.0 Beta)
https://code.google.com/p/android/issues/detail?id=55863
But the way you are using your library in dependency will only work if your library is on central maven repository or in the local maven repository.
Refer this for How to use local maven repository to use .aar in module dependencies.
http://www.flexlabs.org/2013/06/using-local-aar-android-library-packages-in-gradle-builds
This is for Kotlin DSL (build.gradle.kts) assuming you put the files in my-libs subdirectory relative to where the build file is located:
dependencies {
implementation(
fileTree("my-libs/") {
// You can add as many include or exclude calls as you want
include("my-first-library.aar")
include("another-library.aar")
// You can also include all files by using a pattern wildcard
include("*.jar")
exclude("the-bad-library.jar")
}
)
// Other dependencies...
}
For more ways to do this, see Gradle documentations and this post and this post.
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".