I Heart roboguice

Since I was introduced to it by @ahsteele, I’ve been in love with the simplicity that roboguice provides for Android development. It introduces the inversion of control principle to your app and much of the Android SDK. With a bit of configuration, you can remove the explicit calls to get resource objects, shared preferences, etc. and instead simply inject them with the use of simple decorators.

For instance, let’s say you needed access to a shared preferences instance. Traditionally, one would need to request a shared preferences object from a context and store it as a member in onCreate or request it every time it’s needed using one of the methods below:

class SomeActivity extends Activity
{
   SharedPreferences prefs = null; // class member
   protected void onCreate (Bundle savedInstanceState){
      super.onCreate(savedInstanceState);
      // Method 1:
      prefs = getSharedPreferences("some_key", MODE_PRIVATE);
      // Method 2:
      prefs = PreferenceManager.getDefaultSharedPreferences(this);
   }
}

But with roboguice configured, this class simplifies to:

class SomeActivity extends RoboActivity
{
   @Inject SharedPreferences prefs; // equivalent to method 2 above
   protected void onCreate (Bundle savedInstanceState){
      super.onCreate(savedInstanceState);
      // nothing to do here!
   }
}

This can be done outside of an activity class and will use the application context capture the proper SharedPreferences object.

Resources can also be injected, avoiding the need to use findResourceById and cast the resulting object like this:

      // inside method
      Button b = (Button)findViewById(R.id.myButton);

Instead, you can just use the @InjectView decorator:

   // class member
   @InjectView(R.id.myButton) Button b;

You can find some additional examples on the Google Project site. I’ve ended up using roboguice on all of my recent Android projects and haven’t looked back; it makes Android code more succinct and I have discovered that I am a big fan of Inversion of Control in my own code.

2 thoughts on “I Heart roboguice”

  1. I have a non-Activity class that I’m trying to inject SharedPrefs into (my HttpClient singleton). Do you know how I could @Inject SharedPreferences prefs in non-activity classes?

  2. Sorry for the delayed response, but we were able to inject SharedPreferences into our non-activity singleton class without much hassle using the following code:

    @Inject SharedPreferences sharedPreferences;

    SiteAuthCookie.java

Comments are closed.