Wednesday, December 18, 2013

Android Studio, Gradle, and JARs

Everything seemed a bit easier in Eclipse when I first started programming for Android. I knew all my shortcuts and where to find things, and everyone was using Eclipse, so all it took was a quick search on Google to find anything that was unclear.

But then I moved to Android Studio, and of course, I was completely lost.

We had to move over to Android Studio when I was in the training phase of my new job, as that's what my instructor used. It was a welcome change, though, as I knew that's the direction Android was moving to eventually. I was just a bit hesitant because it wasn't even at version 1 yet... hell, it wasn't even at 0.5. But, I've learned to love it. I actually tried to go back to Eclipse just yesterday... I forgot all my shortcuts, and it looked funny.

One of those things I had to get used to was using JAR files instead of the library projects I was used to. In Eclipse, when I made a library, I just referenced the project in my other projects. Maybe I hadn't gotten far enough, but I never had to make a JAR file to use it in other projects. Of course, it's completely different in Android Studio. In our projects, all of the libraries we used had to be from JARs, and had to be included with many little steps and Gradle... I won't expand on my dislike for Gradle right now, but it was very annoying to have to learn this weird thing in order to make my Android apps.

This post is about making JARs for your libraries, something I had to learn how to do for the previous blog post. Took me two whole days to figure out everything I needed. Was even tempted to learn how to code with Gradle, but luckily I didn't have to too much.

Making a library project into a JAR

The library project I made only has two classes in it, so it was pretty simple for me. I'm hoping the process is pretty similar if your project has more complexities to it.

In your build.gradle file, there's a line towards the beginning that should say
apply plugin: 'android'
 You want to change this to
apply plugin: 'android-library'
To be honest, I'm not 100% sure this is needed, but one of the many MANY tutorials I came across had this, so this was in my build.gradle from the beginning. (Hindsight Note: I remember which tutorial. It's in the section about creating AARs)

Another bit I had to add to my build.gradle is this snippet of code from this StackOverflow Q/A:

sourceSets {
        main {
            java {
                srcDir 'src/main/java'
            }
        }
}

Because my project only had classes, this was all that's needed, but according to another question/answer (which I also used for making the JAR), if you used other resources, you might want yours to look something like:
sourceSets {
        main {
            java {
                srcDir 'src/main/java'
            }
            resources {
                srcDir 'src/../lib'
            }
        }
    }
}
This setup is required to use the tasks that come next.
task clearJar(type: Delete) {
    delete 'build/libs/ProjectName.jar'
}
 
task makeJar(type: Copy) {
    from('build/bundles/release/')
    into('build/libs/')
    include('classes.jar')
    rename ('classes.jar', 'ProjectName.jar')
}
 
makeJar.dependsOn(clearJar, build)
All I did for my own library was substitute ProjectName for the name I wanted the JAR file to be. I'm not completely sure of the naming convention, but all the library JARs I've seen were lowercased and hyphen-separated, so I named mine "nfc-utility."

That's it (for just the library JAR). In order to actual get your JAR, in a terminal, navigate to your project where the gradlew file is and type the following line:
./gradlew makeJar
That's it. If/once it's completed, navigate to your project and you'll find that in your build/libs folder if your JAR file.

Making Javadoc and Source JARs

This was a bit difficult for me to understand, and is the part that made me consider trying to learn to do a bit of programming with Gradle. I had gotten the JAR to work in the original project and was excited! But when I hovered over a method, no Javadocs were shown, even though I made sure to document it. Apparently, you have to include SEPARATE JAR files if you want to include Javadocs, and another one if you want the source to be available (trying to look at the source of the original JAR in another project will simply show global variables and method names, everything else masked with "compiled code").

I finally found this StackOverflow answer which I was able to use, but of course it caused some confusion for me: this question and answer aren't related to Android.
task sourcesJar(type: Jar, dependsOn: classes) {
    classifier = 'sources'
    from sourceSets.main.allSource
}

task javadocJar(type: Jar, dependsOn: javadoc) {
    classifier = 'javadoc'
    from javadoc.destinationDir
}

artifacts {
    archives sourcesJar
    archives javadocJar
}
Of course, this will NOT work in our Android project. I was able to rewrite the task for sourcesJar, using hints from the previous makeJar task. And some of the comments on the answer stated that the dependsOn wasn't needed (which is good, as it never ran with those included).
task sourcesJar(type: Jar) {
    classifier = 'sources'
    from android.sourceSets.main.java.srcDirs
}
I had to cheat to get the javadocJar task to work, as I could not figure out how to properly format the from using the code from before. It's okay, though... it worked, lol. If anyone has any tips on how to get it to work properly with proper code, PLEASE let me know.

task javadocJar(type: Jar) {
    classifier = 'docs/javadoc'
    from 'build/docs/javadoc'
}
The from in the task is essentially just a string to the actual location, so I hard coded it. I'm not sure what classifier is for. I thought it was the a folder name, but the folder name for the sourcesJar is NOT sources, it is in fact source in my project... All I know is that with these two JARs, I have my Javadocs on hover and the source is included. I'm not sure exactly how it works, all I know is that it does. Ah, the life of a programmer.

Once again, I'm not sure of the naming convention, but upon looking at the GSON library, their Javadoc and Sources were named by the lowercase, hyphen-seperated way, adding -javadoc or -sources to the associated name before the .jar (mine looked like nfc-utility-javadoc.jar and nfc-utility-sources.jar)

Bonus: AAR!

I was going to wrap up here, and then I remembered about AAR files. I never actually got it to work in my project, but the actual creation is VERY simple. No new code, really. This blog post is what caused me to change the apply-plugin from android to android-library. Just find your gradlew and run these commands:
./gradlew clean
./gradlew aR
Not sure if you have to clean it, but it's probably best to. Your AAR file will be in your build/libs folder.

Again?: Renaming outputed JARs with Gradle!

I'm quite surprised at myself. I went to update the JAR files with some new code and was annoyed that I had to rename the javadoc and source JARs each time. So... I wrote some Gradle code to do it for me, AND move it! Needless to say, I'm a bit excited. I used the sample code in the Gradle docs.


task renameJars(type: Copy){
    from('build/libs'){
        include 'nfc-utility.jar'
    }
 
    from('build/libs'){
        include 'NfcUtility-sources.jar'
        rename 'NfcUtility-sources.jar', 'nfc-utility-sources.jar'
    }
 
    from('build/libs/NfcUtility-docs'){
        include 'javadoc.jar'
        rename 'javadoc.jar', 'nfc-utility-javadoc.jar'
    }
 
    into '../'
}
The code isn't difficult to understand, really. The from looks in that directory, include-ing whatever file or files you specify. The ability to rename is there as well, and I rename my files to the appropriate names. And finally, I say into where I want them placed. I tried a lot of combinations in order to find out how to place them in my current directory, come to find out I just had to use my command-line knowledge. And I call it with


./gradlew renameJars
Another edit!: This Gradle scripting this is actually pretty cool. By making the very first line of the renameJars task look like this
task renameJars(type: Copy, dependsOn:makeJar){
You only need to run this ONE command, and it will not only make your JARs but it will rename and move them as well. I think I'm going to have to make another blog post about this soon...

Another!: Including JARs in your project

Your project more than likely has a libs folder in it already; if not, create one on the same level as java and res. In this folder, add the library jar you want included in your project. Right click and select "Add as library". 

In your build.gradle, add the following line in your dependencies:
compile files('path/to/the/lib.jar')
Normally, every time we did this, we closed the project fully, did a gradlew clean, then opened the project again. There's a way to get Android Studio to do this refresh automatically, but I don't recall the way to do it. Opening the project again should allow you to use the library.

To add sources and javadocs to the library, find the associated JAR files. I added them to my project in the libs folder, though inside of a new folder called docs (the name doesn't matter). This StackOverflow question/answer has another method of doing it (one I tried first with no success) but it states that you should NOT put the javadoc and source JARs in the same folder as the library JAR, so I didn't. Android Studio provides a VERY easy way to include the javadoc and source JARs.

In File -> Project Stucture, select your library. At the bottom, there are four icons: a plus, a plus with a globe, a folder, and a minus. Click on the plus, and add your javadoc and source JARs. If they're correct, Android Studio will know what they are and label them accordingly. Very, very simple.

Conclusion

I felt like I needed to document this all in one space, as I took a combination of two or three different StackOverflow questions/answers in order to get the full effect I was looking for. Once again, if anyone reading this has any improvements or suggestions for me, please let me know!

No comments:

Post a Comment