Where are my assets?


I have a quick post today while I work during my holiday. (I don’t want to forget this tip!) If you have an Android app that uses files from the assets folder and you want to inspect whats in the assets folder during runtime use something like the following:

activity.getAssets().list("")

This will get you a list of everything directly under the assets folder bundled with your app. Do NOT do something like this:

activity.getAssets().list("/")

…as this will get you a list of everything bundled outside the assets folder and confuse you. I did this earlier and saw the actual “assets” folder in this list so I thought I could do this:

activity.getAssets().list("assets")

…or this:

activity.getAssets().list("/assets")

Neither which gave me what I wanted. Again, the magic method call is this:

activity.getAssets().list("")

Getting stabbed by Dagger on Android


Did you read the title? It says I got stabbed, by Dagger, on Android. The non-technical reader would assume something serious occurred followed by hospitalization. Those who know me are already wondering what’s going on with the dependency injection framework I’ve come to love and how it could have any pointy edges. While I actually have physically been stabbed in the not too distant past (long embarrassing story and I don’t wanna get into it) I can assure you today’s situation does not involve anything breaking my skin. Hi, I’m Cliff. You’re here because you’ve been stabbed by Dagger. You may not need bandages or medical care but it hurts kinda bad. I’m here because I was bleeding a little while ago and I want to share my experience.

The catalyst for today’s post revolves around the suspicious error messages I was seeing from Dagger from time to time. I sort of know how to use it pretty well but when I’m in a rush I tend to make subtle mistakes that lead to even more subtle but hard to decipher error messages. These errors don’t always steer me to the source of the problem, rather they leave me with a feeling of, “that doesn’t make sense!” As Dr. House says, “When something doesn’t make sense, one of your assumptions is flawed.” (I love House!) All rambling aside, let’s get to the important part. Below I’ll list a few error messages along with what they might be trying to tell you. Remember, the best way to debug a program is to force an error early on and get used to the random messages it generates. (Tip #2 from my debugging tips.) I’m saving you a bit of time by doing some of this rework for you in Dagger.

Error:
java.lang.IllegalArgumentException: No inject registered for members/com.your.package.YourInjectedClass. You must explicitly add it to the 'injects' option in one of your modules.

at dagger.ObjectGraph$DaggerObjectGraph.getInjectableTypeBinding(ObjectGraph.java:302)
at dagger.ObjectGraph$DaggerObjectGraph.inject(ObjectGraph.java:279)
at com.your.package.YourInjectedClass.init(YourInjectedClass:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)

Cause:
You may have tried to inject a class that is not declared in the Module you’re using to do injection. For eg., if you call ObjectGraph.create(MyModule.class).inject(this); and this object does not appear in MyModule then you probably should add it to the @Module annotation like so:
@Module(library = true, injects = YourInjectedClass.class)

Error:
Compilation completed with 1 error and 0 warnings in 2s 455ms
/Users/you/src/YourProject/src/test/java/your/package/YourInjectedClass.java
Error:Error:line (37)java: your.package.someInjectedDependency could not be bound with key your.package.someInjectedDependency required by YourInjectedClass for YourInjectedClassModule

Cause:
You may be missing a providing method in our module or more likely you’ve forgotten the @Provides annotation. If YourInjectedClass decades an injected variable of type your.package.someInjectedDependency, check that your.package.someInjectedDependency is returned from some providing method and that the method includes the @Provides annotation like so:

@Provides
public someInjectedDependency providesSomeInjectedDependency() {
return new someInjectedDependency();
}

Error:
java.lang.UnsupportedOperationException: No no-args constructor on at com.your.package.YourInjectedClass$YourInjectedClassModule$$ModuleAdapter

at dagger.internal.ModuleAdapter.newModule(ModuleAdapter.java:58)
at dagger.internal.Modules.loadModules(Modules.java:41)
at dagger.ObjectGraph$DaggerObjectGraph.makeGraph(ObjectGraph.java:174)
at dagger.ObjectGraph$DaggerObjectGraph.access$000(ObjectGraph.java:138)
at dagger.ObjectGraph.create(ObjectGraph.java:129)
at com.your.package.YourInjectedClass.setUp(YourInjectedClass.java:22)

Cause:
I got this error by doing something really strange/non-standard. It just means that it cannot instantiate your Module class. In my case I had defined my module class in the same file as the class that was asking for injection but outside the class definition. (This is outside the last curly brace enclosing the contents of the class’ methods.) I then moved inside the class definition but forgot to make it a static. This caused Dagger to not be able invoke the constructor because that only works for static inner classes… if none of this makes any sense to you don’t think about. Just know that the error above means that you should check the visibility of your module class (eg. is it a private class or a public class? Does it have a public no-arg constructor? Is it in the classpath?)

There’s other weird errors I’m trying to get used to and I’ll either post here or write a new article as I discover them.

Swift on Android?


SwiftDroid

I spent some time a couple of months ago catching up on Kotlin, the new programming language from Jetbrains. For those who don’t know, Jetbrains is the company behind IntelliJ Idea, which is the technology that powers Android Studio and a whole bunch of other Integrated Development Environments (IDEs) on the market.  Now news has it that the Swift programming language is coming to Android. The headlines I’ve recently seen say that Google may be considering supporting Swift on Android.  I just searched the web and found this pull request from a day ago. Hi I’m Cliff. You’re here because you don’t know which programming language to learn to start your new career as a software engineer. I’m here because I’m having a blast following the excitement around this new Swift movement.

If you’re new to programming this may all sound like Greek to you. After all, who cares about a Swift, Kotlin, and who even knows what’s Groovy these days? You just want to make the next killer app, or possibly get an icon in the various mobile stores for your business, right? Now you have all of these choices. You can currently write Android apps in Java, C/C++, Go, Groovy, Kotlin, and now Swift is becoming a reality? It can definitely feel overwhelming! Let me assure you that each of these options are certainly important and it doesn’t hurt to do a bit of research before jumping in any boat. I’ll explain some of the more popular choices at a high level then briefly speculate on what the introduction of Swift could mean.

Java
If you are brand new to programming you can’t go wrong choosing Java for your Android app. It is one of the more ubiquitous languages out there and it doesn’t take too much effort to master. Java is supported not just on Android, but also on a myriad of platforms from Mac OS X to Windows and Linux. Java has been around for decades and is currently supported and maintained by Oracle. Java would be the best fit for a brand new Android developer because Android has been designed around this language since the very beginning. All other languages require special features, runtime supporting libraries, and/or work arounds. Almost all of the information and tutorials you’ll find online at the time of this writing is based on Java. All of the Android development editors and tools directly support Java as a first class citizen which makes life painless when you create apps. You get features like auto-completions, syntax-aware editing, and more out of the box when you choose Java. With other languages you only get a limited sub set of these features, if any and many of these features may only available as a bolt-on addition provided by a 3rd party. Java programs currently cannot be used on iOS. (Technically there are ways to make it work but these means go far beyond the scope of what most would consider officially supported.)

C/C++
Why on Earth would anyone want to choose C/C++ for writing an Android app? I’ll tell you why! With C/C++ you get raw speed and your code runs directly on the hardware. If you are new to programming you need to understand how many modern programming languages work. Many program languages are compiled (or, in simpler terms, translated) into raw instructions that a computer processor can understand. These raw instructions are actually random collections of 1s and 0s and referred to as machine code. Languages like Java, Groovy, Kotlin, etc. are not actually converted into machine code, rather they are converted to almost a pseudo code and they use a virtual machine. This is like a mini program that runs your translated program. Both C and C++ compile, or convert to machine code and can be loaded and executed directly by the processor on your phone. This not only makes them run faster, but they tend to consume less memory and have the ability to perform tasks that other languages are restricted from performing. Java is actually somewhat exceptional on Android as the virtual machine it runs on is so highly specialized that it can run at near identical the speed of machine code in some cases. (I don’t have benchmarks, I only go off what I’ve learned from various sources.) Still C and C++ give you the option to interact directly with video and audio hardware on the device. These are also the two programming languages on which many other languages are built. One major reason to choose these languages is that they can be used on just about every platform from Android to iOS, to Windows to even non-standard computing devices like Arduino boards. That said, it requires non-trivial effort to create a program that can be ported to different platforms. Still these languages are more complex than many others and are usually considered for specialist tasks, such as high speed graphical or audio processing, low level network data streaming, etc.

Kotlin/Groovy
Kotlin and Groovy are two powerful scripting languages I have been sporadically experimenting with. They compile, or translate, to Java byte code, which is the same code that Java itself compiles to. They both have advantages over Java in that they are more expressive in terms of the amount of code you need to accomplish a specific task. Where Java tends to use a moderately verbose syntax, these languages pack in incredible amount of power in relatively few verbs and commands. They are also quite flexible in terms of the rules of their syntax. One particular example would be the rules around type checking. Some languages, like Java, C, and C++ enforce rigid rules that type identifiers must be used wherever data is sent around or recorded. Also, in some languages the rules around what constitutes a program statement, or single line of code can be verbose and somewhat unfriendly. Some of these rules are somewhat relaxed and more flexible when using either Kotlin or Groovy and they allow you to combine expressions and statements in an intuitive way to make your logic appear more natural. If you have familiarity with one or more languages or are slightly more than a novice it may be to your advantage to give these languages a shot. It should be noted that these languages are not yet supported on iOS.

Kotlin
Kotlin is developed by Jetbrains, the company behind the technology that powers Android Studio. This gives Kotlin a unique advantage over many of the other choices in that it is treated like a first class language. You get all of the tooling support you would expect from a Java based project when you choose Kotlin. Indeed, there would be little to no difference in complexity when choosing Kotlin compared to choosing Java. While there is a slight learning curve if you are only familiar with Java, the Kotlin community offers plenty of online resources to accommodate.

Groovy
Groovy is developed as an open source programming language with a rather large community of active users. It also happens to be the programming language you use when creating creating Android’s Gradle files which are build time instructions for compiling and packaging your Android app. Groovy brings practically every feature from all the popular languages like Python and Ruby. Groovy also has a rather unique advantage in that it actually borrows most of its syntax and grammar from the Java programming language. This allows for a practically nonexistent learning curve. If you know the Java language you already know 90% of the Groovy programming language! The major differences between Java and Groovy are the relaxed rules in Groovy and additional enhancements. While Groovy also offers many of the same tooling support as Java and Kotlin it comes as an add-on and there is not a ton of tutorials or examples currently available. This could change soon as Groovy takes off.

Go
I don’t know much about Go other than it is a new and growing language developed by Google which, I believe, compiles to machine code. It can be used for Android and iOS but the tooling support is limited, to my knowledge. The Go programming language is also open source and backed by a community of extremely active members, many who live, eat, and pay their income taxes with Go. It is said to be a very simple and powerful language, but again, I am only reporting what I’ve heard. You could choose Go if you wanted to run on iOS and Android, maintain a relatively small code base, and have time to go to the movies. I include it in my round up because of its growing popularity especially among enthusiasts. It is definitely something to keep an eye on.

Swift
This brings us to the Swift programming language. Swift is a relatively new programming language created by and owned by Apple. It has recently been open sourced. While only a few of the languages above can be successfully used on iOS, Swift is actually developed specifically for this platform. Its arrival on Android could mean a variety of things such as no more need to maintain two separate code projects for an app that runs cross platform. The beauty of this new language is that is also is an extremely expressive language which compiles to machine code. Indeed you get the best of both worlds with languages like Swift, where it offers the expressivity and flexibility of Groovy, or Python with the direct execution advantages of C/C++. It’s still too early to speculate on how it will work on Android but the news is already creating a lot of buzz. IT will likely take a bit of time for tooling support to be as complete as it is for Java or Kotlin and few people will trailblazer writing cross platform apps with it. However the possibilities are very enticing. Imagine truly writing code in a single language and deploying it to iPhone/iPad/Apple products along with Android phones and tablets!

This post probably has not answered any questions for you. I am just at the beginning of exploring what my next language of choice will be for Android development. As such, I felt I would convey my thoughts while sharing with many of my new found just learning to code buddies. Many of you may be just starting to code and my hope is that this serves as a gentle introduction to what is currently available. For some of my more seasoned coding homies (y’all are still my peoples!) stay tuned because I plan to do a deep dive into a few of these languages and kick the tires to see what is viable. Until next time…

Android Animation Fun


Merry Belated Christmas!!! I find myself trapped under my Macbook this holiday season and completely captivated by the Android animation system. “I find myself” is sort of a strange thing to say since I’ve never really lost myself. I mean, how can I find myself without involving one of those out of body experiences? If I did have an out of body experience I couldn’t imagine losing myself because I would always know where I last left myself. If myself is not inside my-fleshier-self then I would think that my-fleshier-self would know to stay put until I returned to myself, know-what-I’m-saying? By the way, I’m Cliff. You’re here because you probably did lose yourself on one occasion or another.

You see, not many people are as responsible as I am during out of body experience. Other people would probably misplace their fleshier counterpart while they wander off to the casinos, shorelines and so forth… generally having an awesome time. Then they would circle back, completely forgetting which hospital or state they departed from and… where was I going with the story? Android animation!

I was looking to enhance an app I’m building with animation and when I took a step back I realized I built the beginning of an animation composer. It started from my need to see how the different interpolators behave. I found some source online to visualize interpolation and started to build from it. I had this idea of shape morphing so I created a custom view to see how/what I could do to morph it. My project is somewhat basic. I mean I just started with an activity with an Activity containing animation controls.

A basic activity
A basic activity

I read the values from these controls to make an animator and apply it to a custom view. I then wanted to experiment with orchestrating multiple animations at once or in sequence. For that I needed to repurpose my controls into a fragment so I can create a multi-control list view. Pulling the logic out of my Activity and into a Fragment was somewhat simple using Android Studio. I started by moving the controls in the layout into a separate layout with the extract layout refactoring. This created an includable resource which I wrapped in a FrameLayout. I has to move the animate play button out of the layout with the controls since this would eventually apply to all controls. Building and running on the device confirmed that I hadn’t broken anything while rearranging the layout. I gained confidence to delete the include from my layout. I renamed the activity replacing the Activity suffix with a Fragment suffix and changed the logic to load the newly extracted controls layout. Next I created a simple activity to load the fragment dynamically and add it to a frame layout in the center of the screen.

After confirming the app still worked using the controls out of the fragment I went on to introducing a list view replacing the the included fragment. I figured out how to add fragments as list items in an adapter. I added logic to iterate the fragments in the list and build an AnimatorSet where I play all animations together. Things were broken initially but with a few more tweaks I got the entire thing working again.It is still in its infancy stage but it covers the basics of composing animations and playing them against a custom rounded rect view. You can find my work in progress at Bitbucket.

multiple animation support
multiple animation support

Android custom ViewFactories


So it was three-hundred-twenty-four o’clock one night and I found myself up way past my bedtime trying to hack a custom ViewFactory in Android. Why would I do such a thing? What would I hope to gain? Why couldn’t I just go to sleep? Hi, I’m Cliff. You’re here because you lose sleep working through tough issues on Android. I’m here because I suffer from similar sleep depravation. Today we are going to discuss an unfamiliar, undocumented area of Android called ViewFactories. Disclaimer: I don’t  have any conclusive information on the topic; instead I am in exploratory mode learning as I go. You will not find answers or hidden gems in this article but check back in the future where I hope to have figured out more of the APIs.

We begin by asking the following question: what is a ViewFactory and why would anyone want to wrestle with one? I’m glad you asked. (Technically, I’m just glad you read me asking the question rhetorically.) A ViewFactory is an object that the Android LayoutInflator calls as it parses the layout xml files while inflating views. If you own a ViewFactory then you own an opportunity to add customization as Views are inflated. What can you do when views are inflated? I’m glad you asked that question as well! It brings me to my next topic, the MVVM pattern.

While reading up on the Model View ViewModel (MVVM ) pattern I discovered a tool that advertises easy implementation of the pattern on Android. The tool is called Robobinding and it provides an easy means of binding Java beans-like properties to your layout views as well as binding actions from those views to regular POJOs.  So where we are currently writing code like so:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(rootView);
        this.nameLabel = (TextView)
                findViewById(R.id.name_label);

        if (myPersonModel.getName() != null ) {
            nameLabel.setText(myPersonModel.getName());
        }
        this.nextButton = (Button) findViewById(R.id.next_button);
        ((Button) this.nextButton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myPersonModel.loadNextPerson();
                nameLabel.setText(myPersonModel.getName());
            }
        });
    }

Using Robobinding, you can add custom attrbutes to views in your layouts that automatically update and sync the view with properties in a Plain Old Java Object (POJO). You can also link view events such as onClick to arbitrary methods in your POJO.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:bind="http://robobinding.org/android">
    <TextView
        bind:text="{name}" />
        ...
    <Button
        android:text="Next Person"
        bind:onClick="nextPerson"/>
</LinearLayout>
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        View rootView = Binders.inflateAndBindWithoutPreInitializingViews(this, R.layout.activity_main, personModel);
        setContentView(rootView);
    }
}

What happens here is a custom attribute is added to a known Android view component and these attributes are used to identify properties and actions in the underlying presentation model which should be sync’ed with the view in question. The Activity includes logic that uses a Binders static class method to inflate the views while giving it a presentation model POJO that includes the name property and nextPerson action method. Most of this magic is achieved by using advanced Android concepts like Gradle plugins, AspectJ and Annotations. However, some of the magic happens in a custom ViewFactory. As the views are inflated these attributes are intercepted by special binding objects and used to add logic that reads/writes values from the POJO. That’s just a short description of what this fantastic framework does, but what I find interesting is the ViewFactory part.

I first learned about ViewFactories after hitting a bug with Robobinding that prevents it from working correctly with an AppCompatActivity or ActionbarActivity. That lead me to debugging the framework and walking into its code, which lead me to noticing a problem in how/when the ViewFactories are created in a regular Activity vs an AppCompatActivity, which lead me to rewriting the framework from scratch as an academic or exploratory exercise.

A ViewFactory is part of the Android framework used to create Android View objects from layout files. there is a chain of responsibility that I am beginning to understand where the a Factory can be combined with another ViewFactory in something called a Merger and these factories sometimes delegate to the underlying activity where the developer may want to add their own custom logic for inflating View objects. I don’t know too much beyond this.

What I can tell you now is that you cannot set the ViewFactory in an AppCompatActivity after calling onCreate() in the Activity base class. Instead you must set it before. Also, if you set the ViewFactory before calling Activity.onCreate() you may not be able to get a reference to the LayoutInflater. None of this makes much sense to me, again, I am just learning the APIs as I go along. Hopefully I’ll have more info in the coming days.

Learning Android Gradle Unit Testing


The Gradle build system is pretty robust and it is becoming mainstream. That means it behooves you to start putting it to use. I’d been spending a little time with various Gradle based projects and realized that there were a couple of things missing… documentation on the Android plugin. Sure you can look here but I’m a rebel and I like to pretend there isn’t any documentation while learning the hard way. Hi, I’m Cliff. You’re here because you don’t read documentation. I’m here to show you how to reverse engineer your own documentation using Gradle/Groovy goodness. Today’s article is going to be short since it only covers a small area.

So I’m playing with a Gradle based Android project trying to get unit testing to work when I hit a snag. I had been so used to Maven and following all of the popular Gradle documentation online will have you believing, “Hey this works mostly like Maven!” In fact, a basic Java Gradle project is mostly indistinguishable from a Java Maven project from the outset in that they both follow the same familiar structure. Just drop your compile files into “src/main/java” and your test stuff into “src/main/test”. You hardly have to write any code in your build file to work with these types of projects. So it is almost a given that I get lost when I opened my new Gradle-based Android project and tried to add unit tests. Let’s start from my first sign of trouble in Android Studio. My initial step was to create a test folder for my project to begin adding tests to. Doing so I noticed it was colored manilla-tan and not green as I’d expected. Now in IntelliJ there’s a nice little right-mouse context menu that allows you to mark a folder as either a source directory, a test directory or a resource directory. Right clicking in Andoird Studio did not reveal the same feature so I thought there was a bug in the recent Canary update. (“Doggone Canary bleeding edge!”, is what I murmured to myself in disgust.) Then I thought I could just edit my Gradle build file to get the proper color on my folder allowing me to right click tests and run them directly.

I copied a source set config from an earlier Ant-based Android project that I coerced into Gradle. In this project I used the sourceSet configs to map the legacy Android-Ant structure into something Gradle could work with. This was done many months ago and several changes to Gradle and Android has happened since then but I figured it would still work the same since the original project was still functional. Dropping the following under the android config in my build.gradle did not change the color:

sourceSets {
    test {
        java.srcDirs = ['src/test/java']
    }
}

Out of frustration I poured through all the Gradle documentation I had. Unfortunately I was reading Gradle docs and not Android plug docs for Gradle so I was confused into thinking what I was doing should work. Just before complaining on StackOverflow or filing a bug report I found a little hack I could use to debug my build.gradle. Remembering that a Gradle build is just Groovy source code gave me relief as I could just drop a println anywhere and inspect build elements in my console. (I use the terminal plugin in Android Studio so I didn’t even have to leave myIDE to try it.) I looked up the SourceSet API and then coded the following:

android.sourceSets.each {
    println "Sourceset: ${it.name} java source: ${(it.java ? it.java.srcDirs.join(':'):'Null')}"
}

That’s when it became apparent that there is not test source set in the Android plugin, only an androidTest sourceSet! I also learned, as I had figured, that there was no need to code an explicit source set so long as I followed whatever the convention was. I finally decided to write this blog post out of frustration because NOWHERE IN THE INTERNET UNIVERSE IS THERE ANY DOCUMENTATION EXPLAINING WHERE ANDROID TEST SOURCE LIVES!!! HOw frustrating it is to be an Android developer these days!

Build a better mousetrap (Chat apps)


I’ve been quietly working on a chat app. I built one a long time ago which has been sitting on Github forever without any updates, but I’ve also recently pushed my Android “how to” to Github, you can find it here. I love working in both the Android and iOS space as I get a unique insight that I try to share with others. I also like to compare both the development process and tooling across both platforms. Hi, I’m Cliff. You’re here because you want to build a better chat app. I’m here for much the same reason. With apps like Skype, Line, whatsapp, and others crowding the space you might wonder “what’s the point?” I’m embarking on this experience partly to familiarize myself with what’s changed in iOS 7 but mainly just because. Maybe it will turn into something or maybe it won’t.

I’m my latest effort I’ve actually tried updating Jinx to support iOS7. My first stage has begun with introducing Storyboards and playing with Autolayout. I will later ARC-ify it and rip out the dumb artificial intelligence in favor of what I have in the Android example. Finally I want to incorporate P2P networking, voice recognition and TTS in both apps but that will have to wait until I hit the lottery and can afford to quit my job. (I’m just brimming with ideas!) If you have ideas or insights, feel free to jump in!

Can your IDE do this?


So I’m tapping out a test method in my favorite tool for developing mobile software and it looks like this:

View errorMessage = errorDialog.findViewById(findIdForStringIdentifier(ERROR_MESSAGE_TEXT));
assertTrue("Expecting a TextView field", errorMessage instanceof TextView);
errorMessage.get

Then I notice… no, scratch that I don’t even notice that auto-complete has sprung into action and is offering me the proper completion at the top of the list, “getText()”. It happens in the most subtle way as my subconscious mind already knows what it wanted to do and it directs my fingers to accept the completion. What I end up with is:

View errorMessage = errorDialog.findViewById(findIdForStringIdentifier(ERROR_MESSAGE_TEXT));
assertTrue("Expecting a TextView field", errorMessage instanceof TextView);
((TextView) errorMessage).getText()

Hi, I’m Cliff. You’re here because your IDE doesn’t do what my IDE does. I’m here because I’m ecstatic over what I’ve learned in the last 10 minutes. Look again at the above code snippets, both before and after and follow what happened in between. The important part is where the 1st line establishes a local variable of type “View”. To my amazement auto complete picked up and inferred it was a type of TextView when I started keying the 3rd line and it offered me not just any random or alphabetized list of suggestions but a preferred suggestion that matched exactly what was being conjured up in my grey matter. (For those unfamiliar with Android programming, a view does NOT include a “getText()” method.) And while I didn’t have to futz with the usual, “oh… I have to either declare my local type as a TextView or add a cast” my IDE does this inference then later performs the cast on my behalf keeping my cursor within the proper context so I can continue adding logic. It happened so “matter of fact” like and so quickly that I didn’t catch on until I had completed typing the line at which point I had to do a double take.

How does it know I need a TextView? Is it because of the preceding assert with the “instanceof” comparison? Does it just naturally assume most views will need to be eventually cast to a “TextView” type because that’s all most Android devs know how to use anyway? Is it reading through the xml layout and determining the type based on the integer id returned from my custom “findIdForStringIdentifier” that is taking a String constant id? Has Jetbrains quietly figured out how to read brainwaves over my Mac’s wifi antenna? I don’t know and I don’t really care!

I had done similar programming in other IDEs (Eclipse, Netbeans, X-Code, Visual Studio) but never have I ever had such an experience where an IDE literally read my mind, did the excessive back-spacing, parenthesis wrapping, casting, and continuation of thought for me. It’s these little nuggets that I keep finding in IntelliJ Idea that keep me addicted. I could go on for days on how wonderful this one… read it… ONE experience, out of hundreds of similar experiences, made my life today but I won’t. I’ve argued the merits of Idea to plenty of developers over the years but until you actually experience how do they put it…? “Development with pleasure” Until you actually live out a few of these scenarios you will continue to grind out code the usual way, hitting refresh/rebuild project to clear the red squiggles that really shouldn’t be there, dealing with arbitrary auto-complete suggestions, not truly being able to refactor code effectively as you could otherwise.

Robolectric, Ivy, Maven repo drama


For those of you who know me (which would include most people reading this post) you’ll note that I am a huge proponent of TDD and proper project hygiene. I describe project hygiene as the things you do to ensure a successful project with easy maintenance. I have recently been working to prototype such a project in Android but have been hitting several roadblocks along the way. Hi, I’m Cliff. You’re here because you want a nicely structured project. I’m here because I can’t seem to get my project in the right shape, so I’m complaining.

I started a while ago with an example chat app I had written as a guide to using IntelliJ to write Android apps. I even put up a video tutorial on the subject. I recently had been working to reuse my example which had a hard dependency on the Robolectric project. Robolectric is a cool toy that lets you perform REAL unit tests on Android. There are those who may say, I do unit tests all the tim using Robotium, or the Android JUnit packages… but these are not unit tests as they involve either the emulator or a physical device. The tests I have written run successfully on my laptop and take a fraction of the time that typical Android tests take.

I had my environment working about 7-8 months ago but so much has changed since then. Today when I tried to recreate my magic I had trouble trying to “install” Robolectric on my new Mac. (All my work had been setup on my old Mac.) I originally tried running with the older 1.1 Robolectric jar but then had to tweak my IDE envirnment variables to point to ANDROID_HOME which is so much fun on Mountain Lion these days. (It’s practically impossible to get IntelliJ to see custom system environment variables and the launchctl trick doesn’t work for me.) So the nI eventually decided after forcing ANDROID_HOME and getting a path not found on “~/android-sdk-macosx/platforms/android-10” since my new Mac doesn’t have the older SDKs to install a later version of Robolectric. My thinking was, “maybe they’ve ironed out the details and finally fixed it so you don’t need env variable settings and older SDKs…”

If you visit the Robolectric home page you’ll see all the installation instructions point to a Maven POM. that does you no good if you’re starting from an existing Android project because it either
a.) Forces you to refactor your project using Maven standards
b.) Forces you to reverse engineer the pom to find out where the actual Robolectric jar is.
Both of these options are terrible for existing Android work and since many people rarely get to work on green field this presents a tough dilemma.

I eventually found a way to work around the issue by whipping up an equivalent ivy.xml and throwing together a custom_rules.xml to use in my Android project but it still sux on the surface because of the extra overhead involved with declaring a single Maven dependency in an Android project.

Step 1: create a custom_rules.xml.
Step 2: declare an Ant “-pre-build” target that performs the ivy resolve task and writes the dependecy jar files to your project’s “./libs” folder.
Step 3: create a custom ivy.xml that declares your Maven dependencies.
Step 4: Cuss because you realize it’s not trivial to invoke your custom “-pre-build” target in isolation to test your new configuration.
Step 5: Create a custom “ivy-resolve” target which your new “pre-build” target should now depend on.
Step 6: Test your “ivy-resolve” in isolation to ensure it pulls the correct dependencies.
Step 7: Cuss because your IDE’s built-in version of Ant does not include the Ivy jar.
Step 8: Either find the Ivy jar hidden on your hard drive and dump it into your IDE’s antlib or find your custom ant build tools and point your IDE to that.
Step 9: Repeat step 6
step 10: Cuss because your project’s “libs” folder has now exploded with unnecessary transitive dependencies including everything from ant to maven-model.jar to wagon to xerces.jar
step 11: Try to run your tests and realize that the dependencies declared don’t line up with the examples from the web site.
step 12: construct a blog post expressing your frustrations with the current state of Android development.

In the end I’m wondering why, in the year 2013, we can’t do any better out of the box. Why is it still a chore to practice proper TDD on mobile platforms? (I’m glaring at the iOS community as well because I don’t think that camp is any closer to out of the box TDD.) I would love to just open my IDE, click on a unit test, perform some hotkey combo Cmd+shift+F10 or something, and watch either red or green bars stretch across the screen without considering silly stuff like my environment, grabbing older SDKs, researching dependency matrices and the like.

By the way, I found out how to pull external dependencies into an Android project following this blog post. Nice little trick!

You need permission


You’re writing an Android app and you need to do something slightly more than trivial. Maybe you want your app to snap a picture, maybe you need to capture audio. Maybe you just need to track where the user is. At any rate, your app needs permission to do certain things. Hi, I’m Cliff. You’re here because you’ve asked permission from your user base to do a bunch of stuff. I’m here because I’m learning the ins and outs of Android permissions. Destiny has brought us together and I’m glad to meet you.

I was going to make another long winded post but it’s late and I have other things to do. I’ll just sign off with a link to a site that documents some Android permissions. Maybe you’ll find it useful. You’re welcome!

http://techblogon.com/android-permissions-list-example/#