AndroidAnnotations Nothing Generated, Empty Activity
Asked Answered
D

6

10

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.

Dvina answered 22/5, 2013 at 5:16 Comment(1)
maybe this will help ->linkFortyfour
C
26

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

Cant answered 28/5, 2013 at 22:1 Comment(12)
This is a great solution, especially since it allows for multiple annotations processors. I've changed this to be marked as the accepted answer because of that, but both this and robotoaster's solution work well. Thanks for all the help.Dvina
Wouldn't it be possible to add the generated files to the src paths as well for Android Studio to pick up? Fiddling with project settings defeats the purpose of a build file...Gonnella
Also if your gradle build file uses the packageNameSuffix attribute, you need to add the parameter -AresourcePackageName=yourPackage or your R class wont be find by the AA processor (need latest AA 3.0)Ishii
I am having trouble making this work with android studio 0.1.8 and android gradle 0.4.2, any tips?Oeo
@Shockwave Android Studio does not recognize Activity_ (underscore classes) and the app crushes with java.lang.RuntimeException: Unable to instantiate activity ComponentInfo (...MainActivity_)Oeo
@Shockwave please ignore my comment is all working now, I did a gradleclean && gradle build from consoleOeo
if you dont want to mark the direcotry as source root in Android studio manually, take a look at my answer. the configuration there adds the apt output path to the sourceSets for all buil varaintsLailaibach
@Deekay Update 3 - alternatively use afterEvaluate { project -> android.applicationVariants.each as it is mentioned in android-review.googlesource.com/#/c/62933Legislative
@Legislative Do you prefer this solution over the presented or is it just an equal alternative?Mastership
its just an alternative mentioned by Xavier DucrohetLegislative
This did not do anything for me. Where is it passing the actual processors to execute?Skiplane
Is it still actual? I'm with AS 4.0.2 and getting this error using mentioned build.gradle: "Could not find com.googlecode.androidannotations:androidannotations-api:2.7.1."Tiberius
L
6

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

Lailaibach answered 24/7, 2013 at 17:3 Comment(1)
Note for others using this configuration (which is the one I use). If you decide to later add Flavors to this configuration and rename the package (like com.mycompany.myapp to com.mycompany.myapp.pro), you will likely run into a problem resolving the R.Java class file in the "pro" version. To get around this use the '-AresourcePackageName=MyBasePackageName' parameter to redirect androidannotations to the correct R.Java file. For a more in depth explanation, see #19351668Hallucinosis
L
4

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.

Legislative answered 23/5, 2013 at 18:6 Comment(6)
It seems in 0.4 android.buildVariants was changed to android.applicationVariants. Using this I can build the project fine, but I still don't get anything generated.Dvina
Hi, thanks @robotoaster, this code works in gradle on the command line. However I cannot use the underscored classes in Android Studio since they are generated into a directory, Android Studio is not aware of. Do you have any help?Mastership
in Android Studio open Project Structure and in the module sources select /build/classes/debug/ as source.Legislative
Running with gradle 0.5.0 I get Annotation processor 'org.androidannotations.AndroidAnnotationProcessor' not foundOeo
do you run it from command prompt "gradle assembleDebug" or similar?Legislative
Thanks, works fine for me with the latest version of the plugin and Android Studio.Skiplane
G
4

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+"
}
Gymnast answered 31/1, 2014 at 23:7 Comment(1)
They just reverted my wiki changes. I'm trying to figure out what I did wrong.Gymnast
O
3

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

Oeo answered 2/7, 2013 at 8:44 Comment(2)
yeah a bit hacky but it works. I had a weird behaviour with it building twice.Randolf
@RomainPiel try gradle clean && gradle build sometimes it helpsOeo
B
0

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".

Bead answered 16/7, 2013 at 13:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.