Android Dagger 2 Dependency Injection Tutorial

What is Dependency Injection in Android? Dependency Injection is a practice where objects are designed in a manner where they receive instances of the objects from other pieces of code, instead of constructing them internally. This means that any object implementing the interface which is required by the object can be substituted in without changing the code, which simplifies testing, and improves decoupling. It makes the project more easy to maintain and testable. In this tutorial, I will tell you on how to use android dagger 2 dependency injection in your own project.

For example, consider a Car object.

A Car depends on (uses) wheels, engine, fuel, battery, etc. to run.

Without Dependency Injection (DI):

class Car{
  private Wheel wh= new NepaliRubberWheel();
  private Battery bt= new ExcideBattery();

  //The rest

With Dependency Injection (DI):

class Car{
  private Wheel wh= [Inject an Instance of Wheel (dependency of car) at runtime]
  private Battery bt= [Inject an Instance of Battery (dependency of car) at runtime]
  Car(Wheel wh,Battery bt) {
      this.wh = wh; = bt;
  //Or we can have setters
  void setWheel(Wheel wh) {
      this.wh = wh;

Creating a New Project

1. Open Android Studio IDE in your computer.
2. Create a new project and Edit the Application name to “Dagger2Example”.
(Optional) You can edit the company domain or select the suitable location for current project tutorial. Then click next button to proceed.
3. Select Minimum SDK (API 15:Android 4.0.3 (IceCreamSandwich). I choose the API 15 because many android devices currently are support more than API 15. Click Next button.
4. Choose “Empty Activity” and Click Next button
5. Lastly, press finish button.

Add new dependency

Open your Gradle file and add dagger 2 library in the dependency section.

compile ''
annotationProcessor ''

Create ToastUtil class

Create a new class file name “ToastUtil” and Edit this class to the sample source code.

public class ToastUtil {

    private Context mContext;

    public ToastUtil(Context context){
        this.mContext = context;

    public void showToast(String message){
        Toast.makeText(mContext,message, Toast.LENGTH_LONG).show();


Create Application class

After that also create an application class to init the dagger app component to all activity.

public class App extends Application {

    AppComponent mAppComponent;

    public void onCreate() {

        mAppComponent = DaggerAppComponent.builder().appModule(new AppModule(this)).build();


    public AppComponent getAppComponent(){
        return mAppComponent;

Create an AppModule class

Add another new class for AppModule, this class provides the context and ToastUtil instances to the whole app.

public class AppModule {

    Context context;

    public AppModule(Context context){
        this.context = context;

    public Context provideContext(){
        return context;

    public ToastUtil provideToastUtil(){
        return new ToastUtil(context);


Create an interface

Create a new interface “AppComponent”, this interface is to get all the instances provide by the module class.

public interface AppComponent {

    Context getContext();

    ToastUtil getToastUtil();
//    Test test();


Create MainModule class

This class is for MainActivity, it provides the static text to the MainActivity.

public class MainModule {

    public String providesHello(){
        return "Main Hello";


Create PerActivity annotation

This annotation is to make sure only perform when the activity is running.

public @interface PerActivity {

Create a new interface

Create an interface “MainComponent”, this component will inject the mainActivity class, so that you can get the helloText from the MainModule.

@Component(dependencies = AppComponent.class,modules = {MainModule.class})
public interface MainComponent {
    void inject(MainActivity mainActivity);


Edit MainActivity class

Go to this file and edit this file to the following code. It will display 2 difference toast.

public class MainActivity extends AppCompatActivity {
    private MainComponent mMainComponent;
    ToastUtil toastUtil;

    String helloText;

    protected void onCreate(Bundle savedInstanceState) {

        mMainComponent = DaggerMainComponent.builder().appComponent(getAppComponent())
                .mainModule(new MainModule())

        toastUtil.showToast("Custom Toast Message");


    public AppComponent getAppComponent(){
        return ((App)getApplication()).getAppComponent();

Edit AndroidManifest.xml

Add android:name =”.App” so that your project will run this file on the beginning.

        <activity android:name=".MainActivity">
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

Run Your Project

In conclusion, now you can check it out how the dagger 2 works in this project. Run it on your emulator.

(Android Dagger 2 Dependency Injection)

Source Code

(Visited 919 times, 1 visits today)

Yong Loon Ng

Ng Yong Loon, better known as Kristofer is a software engineer and computer scientist who doubles up as an entrepreneur.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *