in Android

Guice for Android, dependency injection made easy with roboguice!

Today morning, as I was reading the news, I saw an article on Guice, Google’s open source framework for Dependency injection in Java.

Hey, Android uses Java too, is there any dependency injection framework for Android?

Hopefully, the answer was only one search away, so I found roboguice.

roboguice slims down your application code. Less code means fewer opportunities for bugs. It also makes your code easier to follow — no longer is your code littered with the mechanics of the Android platform, but now it can focus on the actual logic unique to your application.

See an usage example of roboguice:
Without guice:

class AndroidWay extends Activity { 
    TextView name; 
    ImageView thumbnail; 
    LocationManager loc; 
    Drawable icon; 
    String myName; 

    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        name      = (TextView) findViewById(R.id.name); 
        thumbnail = (ImageView) findViewById(R.id.thumbnail); 
        loc       = (LocationManager) getSystemService(Activity.LOCATION_SERVICE); 
        icon      = getResources().getDrawable(R.drawable.icon); 
        myName    = getString(R.string.app_name); 
        name.setText( "Hello, " + myName ); 
    } 
} 

With guice:

class RoboWay extends GuiceActivity { 
    @InjectView(R.id.name)             TextView name; 
    @InjectView(R.id.thumbnail)        ImageView thumbnail; 
    @InjectResource(R.drawable.icon)   Drawable icon; 
    @InjectResource(R.string.app_name) String myName; 
    @Inject                            LocationManager loc; 

    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        name.setText( "Hello, " + myName ); 
    } 
} 

I love it!

Share