Dagger 2 Android Example using Retrofit : Injecting Dependency

Struggling with Dagger 2? Don’t know how to implement it in your Android Project? Don’t worry, here am I with this Dagger 2 Android Example.

So, today in this Dagger 2 Android Example we will modify one of our previous project to learn the Dependency Injection Architecture.

The post is for beginners, who just want to get into the design patterns.

In this tutorial, we will work on Retrofit Android Example project that we created in one of the earlier posts. So it is highly recommended that you should go through that tutorial first and get the source code of that project.

What is Dependency Injection?

Dependency Injection is a design pattern, or you can say a concept of Object Oriented Programming, where we don’t create an object of another class inside a class using the new keyword (for Java). Instead, we supply the needed object from outside.

In the previous post, Android Dependency Injection we learned the conceptual thing about Dependency Injection in detail. So if you are entirely unaware of this stuff, you should go through the previous tutorial first.

What is Dagger 2?

Dagger is a fully static, compile-time dependency injection framework for both Java and Android. It is an adaptation of an earlier version created by Square and now maintained by Google.

I guess Dagger 2 is the most popular dependency injection framework currently available. And it is now maintained by Google, so you should learn it.

Working with Dagger 2

Before moving ahead in our Android Project, let’s understand first that how we work with Dagger 2.

So we have three major things in Dagger.

#1 Dependency Provider

Dependencies are the objects that we need to instantiate inside a class. And we learned before that we cannot instantiate a class inside a class. Instead, we need to supply it from outside. So the person who will provide us the objects that are called dependencies is called Dependency Provider.

Confused? Don’t worry it is not a real person :P. It is a regular class that will provide the dependency.

And in dagger2 the class that you want to make a Dependency Provider, you need to annotate it with the @Module annotation.

And inside the class, you will create methods that will provide the objects (or dependencies). With dagger2 we need to annotate these methods with the @Provides annotation.

So remember the annotations @Module and @Provides.

#2 Dependency Consumer

Now, we have the dependency consumer; it is a class where we need to instantiate the objects. But now we don’t need to instantiate it with the new keyword (I am assuming java here). We do not even need to get it as an argument. But dagger will provide the dependency, and for this, we just need to annotate the object declaration with @Inject.

#3 Component

Finally, we need some connection between our dependency provider and dependency consumer.
For this, we will create an interface by annotating it with @Component.  And rest of the thing will be done by Dagger.

Is everything confusing? Don’t worry you will get things cleared after implementing in the Android Project so keep reading.

Dagger 2 Android Example

Now let’s refactor the application that we created in the earlier Retrofit Example Tutorial.

This time we will not create a new Project, so just go to the following link and download the Source Code, then open it in your Android Studio. And then you are ready to move ahead.

Retrofit Android Example – Fetching JSON

Adding Dagger2 to Project

The first step is obvious that we need to add the Dagger2 to our project.

  • So in the project that you opened go to app level build.gradle and inside the dependencies block add the lines shown below.

  • Sync the project with gradle.

Creating Modules

For this project, we need two modules. The first one is the App Module, and the Next one is API Module.

App Module

This module will provide the Context. You already know that we need Context everywhere, and in Retrofit as well we need the context object. And as the DI rule says we need an outsider to supply the objects, so here we will create this module that will give us the Context.

  • Create a new class named AppModule and write the following code.

  • The above code is straightforward, and we just use a new thing @Singleton. In dagger, we have this annotation, when we want a Single object. I guess you already know about Singleton. With the dagger, you just need to annotate @Singleton when you want a single instance only.

API Module

We need many objects in this Module. You might already know that for Retrofit fit we need a bunch of things.
We need Cache, Gson, OkHttpClient and the Retrofit itself. So we will define the providers for these objects here in this module.

  •  So, create the class named AppModule and write the following code.

We have done with the Modules. Now let’s define the Component and then we will inject the objects.

Building Component

  • Now, we will create the Component.

  • So you can see we will inject in the MainActivity. We also define all the modules using the @Component annotation as you can see in the code.

Before moving ahead Rebuild your project. 

  • Now create a class named MyApplication. In this class we will build the ApiComponent.

  • Note that we are using the same project, with no additional changes. So make sure you are working, on the same project. The URL we are using in the above code to fetch JSON is working and you can use the same. 
  • So, we have our API component, but we need to instantiate this class when our application launches. And for this, we need to define it inside our App Manifest file. So open your AndroidManifest.xml and modify it as shown below.

Dagger 2 Android Example

Injecting Dependency with Dagger 2

Now finally, we can inject the dependency.

  • Come inside MainActivity.java and modify it as below.

  • Now you can try running your application.
Dagger 2 Android Example
Dagger 2 Android Example
  • So, it is working fine.

You might be thinking “WHAT THE HELL? I did all these big changes to do nothing”. 😛 But trust me it makes life easier when working on some big projects. 

What we learned in this post is following an architecture. You will get the usefulness of this thing when I post about some Advanced Android App Design Pattern like MVP or MVVM.

Dagger 2 Android Example Source Code

So, guys, I hope you understood the basic idea that how we work with Dagger 2. But still, if you are having any trouble following the codes you can get my source code from GitHub.
To get the link, you need to unlock it using one of the SHARE buttons.

So that’s all for this Dagger 2 Android Example friends. I hope you found it useful if you did, then please SHARE this post with your friends.
If you have any question regarding this Dagger 2 Android Example, then leave your comments, and I will try to help you. Thank You 🙂

20 thoughts on “Dagger 2 Android Example using Retrofit : Injecting Dependency”

    • You missed that line I’ve written in BIG BOLD RED letters that before moving ahead rebuild your project as Dagger generates it on compile time. So go to build -> rebuild the project then you will find the DaggerApiComponent.

      Reply
      • Hi Belal,

        I am getting the same error even u have already add the name in manifest class and already rebuild the project and even invalidate and restart the project until then getting same issue .That issue has been diminished my whole day and getting worried because i have to deliver my project.

        Reply
  1. Your tutorial is awesome.thank u so much for this please share the next tutorial for MVP and MVVM architecture.i am eagerly waiting for that.

    Reply
  2. .appModule(new AppModule(this))
    .apiModule(new ApiModule(“https://simplifiedcoding.net/demos/”))
    Both module are deprecated, any suggestions?

    Reply
  3. It’s a great artical I ever learn on dagger 2
    Just make a small correction you wrote AppModule in place of ApiModule in side the description I was Little confuse when I read it

    Reply
  4. If I need the Retrofit instance in 2 activities, for example, MainActivity.class and DetailsActivity.class,
    Do I need to do the following?

    @Singleton
    @Component(modules = {AppModule.class, ApiModule.class})
    public interface ApiComponent {
    void inject(MainActivity activity);
    void inject(DetailsActivity activity); // *Do I need to add this line..?*
    }

    If I need retrofit in 10 different activities, is the above a standard solution to do so?

    Reply
  5. Wow great explanation but i didn’t understand correctly i will check that slowly step by step,Thanks for helping developers like to sharing your knowledge.

    Reply
  6. Hi Belal Khan,
    Your tutorial was great help full to understand the Dagger. Thanks for the awesome Explanation.

    I have a doubt can you please help me to clarify it, what if i have multiple activities and how do we inject Retrofit into all activities. should I keep on injecting all the activities in “Interface ApiComponent” as individual methods.

    Thank you

    Reply

Leave a Comment