IoC and DI in Android using RoboGuice

Recently I started looking at Inversion of Control technique using Dependency Injection. In Java there is a great tool called Google-Guice. This tool is great for creating more testable, modular code. There is a porting to Google-Guice in Android called RoboGuice. This is what I am going to write about here.

Since we (Conduit Mobile) write a platform, our Android and iOS code needs to be designed properly. This means heavy use of design patterns and coding techniques most application developers seldom use (at least to my knowledge – no offence guys). This approach lead me to consider IoC. Since we want our modules to be interchangeable and testable, IoC is a good way to go. When coming to implement it, I came to a dilemma – should I implement it myself, or should I use an existing library. One of the biggest changeless in IoC in Android is the need of Context in many of the objects. RG solved it quite nicely with a neat annotation mechanism.

Contexts and Singletons

I wanted to create a singleton in my app that should depend on the Application Context. The problem is that this context is only available when the app starts. I wanted to avoid bootstrapping the object (some init function that receives a context as parameters). I also don’t like all the repetitive code of the Singleton design pattern. In RoboGuice they solved these stuff using the @ContextSingleton annotation. Sadly, the documentation is behind the code, but after playing with it, it is quite a nice way to implement this. All you need to do is this:

  1. Make your singleton with Context be annotated with the @ContextSingleton annotation.
  2. In the singleton, inject the context using the @Inject annotation.
  3. Make your Activity/Fragment extend the RoboActivity/Fragment.
  4. Inject the singleton using the @Inject annotation.

So, for example:

The RoboActivity will take care of injecting the activity context. You can specify the exact context you want by changing this code a bit and instead of injecting the context directly, use the @Inject on a constructor that accepts a context and get the application context. e.g:

RG also have tons of other cool features that can be useful (View/Resource injection). I plan on using RoboGuice and see how it turns out. Hope I’m not heading for a fall, but it seems better than implementing it all myself.

5 Things I Learned from the AQuery Source

Disclaimer

This is a tribute to Paul Irish’s excellent video 10 Things I Learned from the jQuery Source. I think it is an great video and a good lesson for every developer – get to know the libraries you work with, and if they are open sources, get familiar with the source code. I already posted in this blog about Backbone.js and specifically on Backbone.js Views events. I could not accomplish that w/o getting my hands dirty in BB source code. Also, as Paul points out, this is a great way to learn new tricks. These open source projects are developed by some of the brilliant minds of the industry and there is a lot to learn from these guys.

So w/o further ado, let’s get down to business.

AQuery – you misspelled it

AQuery is (as taken from the AQuery Website): “inspired by jQuery, a javascript framework for web site, hence the name “Query”.” The difference is that AQuery is a library intended for Andoid developers and as such is written in Java.

I first came a cross this framework a couple of days ago when a colleague pointed it up to me. It immediately caught my attention and my team’s Android developer took it on a test drive the day after. We saw immediate results in performance boost and our code became much shorter and simpler. We only just started using it for image downloading and it is amazing. Till now, we implemented a whole “Download manager” component that became more and more complicated over time. With just a few lines of code we managed to make this component redundant and enjoy AQuery doing all the “heavy lifting”.

Inspired by Paul Irish’s video and approach, I started looking at the source code of AQuery, and I saw that not only they did an amazing library, the code is just equally great (thinking of it, it kinda make sense that a great library will be well written). This is how this blog post came to life. Hope you’ll enjoy reading it as much as I enjoyed writing it. I also hope that some of the things will give you new ideas about Android and Java programming.

1. Constants in Interfaces

This is an awesome way to avoid putting constants that you need to share across several classes in one class. I saw this in the AbstractAQuery class that implements the Constants interface. At first I thought: “What an odd way to name an interface”. Then it occurred to me that in Java, interfaces can contain constants, so why not use them this way instead of putting the constants in one of the classes and accessing them from all other classes?

It is important to note that I saw that the Constants Interfaces is considered bad practice (at least by this Stack Overflow post).

2. Generics and Object Creation

To extend AQuery, you need to write the following code:

class MyQuery extends AbstractAQuery<MyQuery> {…}
This, in turn, creates a new MyQuery object each time you use one of the “selector” function such as id. The reason this can be accomplished is the fact that you pass MyQuery as the generic param for the implementation. This is a nice way to implement extend ability.

3. Make it Green – Recycle

This is a very important practice that I already know from the adapters. When using adapters, one of the important parameters in the getView method is the convertView. This enables us to reuse an existing view (that is out of the scope of the screen) instead of creating a new one. The AQuery team also did an optimization that enables you to reuse the same AQuery object in an adapter.

4. Common Listener

Again, a nice trick they use to avoid creating multiple classes. The Common object implements a variety of listeners. This enables them to use the same invoke method for all the listeners. Also, it enables them to use that class as a file comparator, runnable and many other things.

5. Use of Weak References for Handlers

In the AJAX requests, the handlers are saved in a weak reference. This way, if the request is returned after the activity was destroyed, the activity will not leak. This is a very important practice to avoid leaking activities.

Backbone.js Views events

In my previous post I wrote about the Backbone.js library. When creating a view that contained several clickable areas and also anchor HTML elements I noticed that the anchor links did not work. Further investigation using a cool tool called Visual Event led me to the part of the code that interprets the view’s events object. In the Backbone.View constructor, there is a call for delegateEvents function. What this function actually does is go over the events object and use jQuery to bind the handlers to their relevant events. The thing is that in BB the events object has the ability to contain selectors e.g. ‘eventName .class-name’ : ‘eventHandler’. This little difference is quite big in terms of both performance and functionality. At the end of the delegateEvents function there are the following lines of code:

This little line of code makes all the difference. Instead of simply bind the event like he does when there is no selector, BB uses delegate. In the delegate documentation you see this simple explanation: “Attach a handler to one or more events for all elements that match the selector, now or in the future, based on a specific set of root elements.”. It is not by accident that I highlighted the “in the future” phrase. What it actually means is that he attaches a handler on the jQuery object, and when the event is triggered, it uses the selector to find the relevant element inside the element represented by the jQuery element. For example:

This will bind the tap event to all elements with the class=”class1″, and when the event is triggered, it will trigger it only on the inner elements with the class=”class2″. Let’s say that under a class1 element you have this element:

Tapping this element would just not work! You need to bind the tap event manually after the element is added to the view, so instead of writing this:

Which will cause this call:

You should call this:

You should know that there is subtle difference between these calls. In the first one I used “method” instead of this.eventHandler. The reason is that BB does not pass the function as is, but encapsulate it with its own bind method that allows it to pass a context to the method which is basically saying: when you run this handler function, set the “this” object to the one I specify. In the latter line of code, this.eventHandler will have the DOM element on which the event was triggered on as the context (“this” object). To overcome this “this” issue (sorry, couldn’t resist), you can use the jQuery.proxy function, in this case:

What we basically do is change the context of the eventHanler when called. Have a look on the proxy function implementation, pretty straight forward.

There is a lot to learn when looking inside the libraries code (as demonstrated in Paul Irish‘s highly recommended video: “10 things I learned from the jQuery source“). So don’t be afraid to look into these libraries and try not to consider them as a black box. I know I did.

Backbone.js

I’ve been working with a framework called Backbone.js lately, and I really think that you should check it out.

From first glance, it looks that it doesn’t do much actually. But after working with it a day or two it immediately revealed its power. And to my opinion that power comes from its simplicity. It just organize your code in bits that you can reuse and manage with ease. I found that I write much better code faster.

Backbone.js (or in short BB) is an JS implementation of the MV(C) model. When writing a heavy JS app, BB is your friend. The reason that I put the “C” in parenthesis is that BB does not have that part of the MVC design pattern (the “Controller”).

Only thing I lack is a “Controller” in the MVC structure. But basically, I don’t miss him that much.

So try it out, very simple to learn and really improves your app.

Android WebView/Browser and Orange Rectangles

Wrote an answer to this on StackOverflow, but thought I should add it here as well.

First: The Problem

Orange rectangles appear when you select a link on a WebView/Browser. This is due to Android Touch Mode. What it basically does is let you know that the link is selected. This is an annoying problem and there are two ways to overcome this issue.

Therefore: The Solution

Two actually in this case:

  1. The Java/Native Approach: Call the webView.setFocusableInTouchMode(false). This only solves it half way and in the WebView where you run your HTML only. Also,  You should take into account though that this solution will make all text input boxes in your webpage unavailable.
  2. The CSS/Web Approach: Set the following css property: -webkit-tap-highlight-color:rgba(0,0,0,0); This will not cause the problem with the input boxes. But in this case you’ll need access to the HTML code you are running (though you can inject this to the HTML anyway).
That’s it,
Enjoy and till the next post…

ADT Graphical Layout tool and SCM systems

Well, most of you android developers encountered this problem. The graphical layout designer in the ADT (Android Developer Tool – the eclipse plugin) creates every element in the XML as one line. You might ask, why is it a problem? well, in most cases, it is not. But there is one annoying thing that makes this feature/bug or whatever you want to call this a real time consumer. Unless you are a solo Android developer that saves his code in a local or remote storage as is, you probably use some kind of SCM (Source Control Management) system (e.g. git, svn, cvs, tfs, clearcase and the list goes on and on). Most (if not all) of these systems and their diff tools (also most of the diff tools I encountered) use line comparison. They tell you if you added/removed/edit a line. In case you edit a line, it marks the parts of the line you edited. This is all nice when you edit the text code yourself. But in the GL (Graphical Layout) you don’t. And then, if you changed one property of an element using the GL, you will see it in the SCM as an edited line. The thing is, now you need to go over the whole element (that sometimes has several properties) and see which property exactly you changes. And let’s say, for example, that you changed two properties. One is at the beginning of the line and the other at the end. How easy it would be to miss that second property? Basically, what the GL does is to eliminate many of the advantages of SCMS.

In the past, I usually chose between two options:

  1. Not use the GL (not always possible since I don’t remember all the properties by heart).
  2. After using the GL, go over the file and add line breaks manually.
I wanted to use the auto formatting tool of eclipse, but it always looked bad. Here it how it looked before:
And After:
After a bit of digging in the eclipse preferences by my colleague he found the solution: going to preferences -> XML -> XML Files -> Editor and checking the “Split multiple attributes each on a new line” and after pressing Ctrl+Shift+F voila:
No more hard work setting the text to align as i want it.
Enjoy.

Mobile Web Debugging

In my current job, I became part of the FED (Front End Developers) community.
In Android there are great debugging tools, and the tools for FED development are improving more and more. I got to know WebKit’s Web Inspector (in Safari and Chrome) and learnt how to use them.
But when running the same web app on mobile devices, I encountered a wall… Suddenly I was compeled to use old fashion debugging techniques like print to log and alerts. Of course some devices don’t natively support even that and you need to implement your own print to log mechanism (fun fun fun).
But help came in the last few days in the name of Weinre. This is a great Web debugging tool that lets you remotely debug your mobile web application with most of the functionality of Web Inspector. Of course, since the “debugger” on the Web App side is actualy a JS script, you can’t put breakpoints and stuff like that, but it eases the working process tremendously.
So enjoy and good work Weinre guys…