Android Presenter To Activity Using Guice
In a prior post I talked about how to unit test android applications. I made some references to wiring up an Activity with a presenter, but I didn’t really show how I was doing that.
I got some requests to show some sample code, so I thought I would explain what I was doing here and see if anyone had better suggestions.
To make it easier to unit test and to decouple my system as much as possible, I am using a dependency injection framework called Roboguice. It is basically the Google Guice framework that is ported to Android and adds some Android specific functionality.
One challenge you will most likely first encounter when working with Roboguice is that a presenter is going to need a reference to the Activity class that is going to represent its view. Since the Activity class has to create the presenter, this presents a dependency injection challenge.
We can’t just ask for a presenter from our container and have it auto-resolve the dependency on the Activity. (That is we can’t rely on constructor injection in this case.)
Setter injection to the rescue
One thing we can do, is use setter injection instead of constructor injection to inject the other references our presenter will need.
Guice provides us with an easy way to perform setter injection after we have created the object. I use this technique to make sure that I can pass my activity into the presenter and still have the benefits of having the other dependencies injected into the presenter.
Here is some code showing my OnCreate method inside my activity.
This code is creating an instance of my presenter which holds a reference to the Activity, or view, it is manipulating. Then Guice injects dependencies using the module I created into any properties that are annotated with @Inject.
Here is what some of those presenter set methods look like:
You can see that they are declared in the module like so:
It’s not exactly pretty, but Android applications are really a loosely coupled sets of Activities which are the entry point into your code. It makes it very difficult to create a MVP type of framework that we might be used to.
If you know of a better way than what I am doing please let me know, and if you have any questions or suggestions, I’m always glad to hear them or help if I can.