Android Dagger 2 Dependency Injection with Retrofit for Beginners

In this android tutorial, we are going to learn how to use Android Dagger 2 dependency injection with retrofit network library in our android application.

This is basically for beginners android developer who want to understand how to use dependency injection in android.

Before we go deeper into the subject, lets first understand what the term Dependency Injection means.

According to Wiki – In software engineering, dependency injection is a software design pattern that implements inversion of control for resolving dependencies. A dependency is an object that can be used (a service). An injection is the passing of a dependency to a dependent object (a client) that would use it. The service is made part of the client’s state.[1] Passing the service to the client, rather than allowing a client to build or find the service, is the fundamental requirement of the pattern.

To further illustrate the definition above. Normally, we are class or a service (dependency) is dependent on another class (dependent), the dependent class will instantiate its dependency when it is created or on calling its method like in the example below.

public class BuildingCost
public class BuildingCost {
    private final double wageCost = 2000;
    private BuildingMaterialCost materialCost;
    public BuildingCost(){
        materialCost = new BuildingMaterialCost();
    public double totalBuildingCost(int materialCount){
        return materialCost.getTotalCostOfMaterial();
public class BuildingMaterialCost{
    private int numberOfMaterials = 1;
    private final double costOfEachMaterial = 200;
    public void setNumberOfMaterials(int numberOfMaterials) {
        this.numberOfMaterials = numberOfMaterials;
    public double getTotalCostOfMaterial(){
        return numberOfMaterials * costOfEachMaterial;

You can see from the code sample above that the BuildingCost class instantiate it dependency class BuildingMaterialCost when it is create. With reference to the dependency class, it can call the class methods.

Where else, if we implement a dependency injection, the object of the dependency class will be created by a third party framework and supply it to the dependent class when needed.

Lets proceed back to Dagger 2. This name might be familiar to you but if you don’t yet understand what it is then a its simplest form, Dagger 2 is a dependency injection library for android. Although it can be use in your Java application.

Dagger inspiration came from Guice but there has been a lot of differences and it is optimized for mobile device.

Dagger 2 has considerable improvement from Dagger 1 which uses reflection where as Dagger 2 depends on code generation. For more information about original of Dagger and the changes in Dagger 2 I will suggest your read the Dagger User Guide.

Our Project Example

In other to get a basic understand of how to use Dagger 2 in your android application, we are going to create an app that fetch data from a remote database and populate it to a recycleview widget.

We are going to use Android Retrofit Library for network call. If you have not use Retrofit before, this will be a good starting point. You can also check out my previous tutorial on Android Retrofit.

We will use Dagger 2 for dependency injection. What this means is that we are going to inject the Retrofit class in our project MainActivity class. Another important feature about dependency injection is that you can inject any dependent object anywhere in your application.

We will create a RecyclerView widget in our project main layout file. Next, we will move on to create a new layout file that will represent each item list in the RecyclerView. Thereafter, we will create RecyclerView Adapter with its corresponding ViewHolder class.

The adapter will bind our data source with the Recyclerview’s list items.

We will go through the process of implementing Dagger 2 in our project and will end up with create a simple web app that will help our application to connect with our remote database storage.

In other to get a visual understanding of what we are going to create in this android tutorial, I have add below some screen shots from the application.


android dagger


Lets start to soil our hands in code. Start up your IDE. For this tutorial, I am using the following tools and environment, feel free to use what works for you.

Windows 10

Android Studio

Sony Xperia ZL

Min SDK 14

Target SDK 24

To create a new android application project, follow the steps as stipulated below.

Go to File menu

Click on New menu

Click on Android Application

Enter Project name: AndroidDagger2Example

Package: com.inducesmile.androiddagger2example

Select Empty Activity

Name your activity: MainActivity

Keep other default selections

Continue to click on next button until Finish button is active, then click on Finish Button.

Now that we have created our project, there are few things we need to do before we start going deeper.


Since our application is going to fetch data from a remote database we will need to add the Internet user permission. Open your project AndroidManifest.xml and add the code below.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
    <uses-permission android:name="android.permission.INTERNET"/>
        <activity android:name=".MainActivity">
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />

Build.gradle for Dependencies and Android-apt plugin

We will move over to the build.gradle file. If you have not used Dagger 2 before then I will suggest you have a look at the tutorial and how to configure / setup dagger in android studio. 

One thing we need to do is to add android-apt in the project level dependencies and in the Module level build.gradle, we will add the android-apt plugin below the android plugin.

Dagger 2 uses the android-apt plugin because of the following reasons

1. Allow to configure a compile time only annotation processor as a dependency, not including the artifact in the final APK or library

2. Set up the source paths so that code that is generated from the annotation processor is correctly picked up by Android Studio.

There are other third party libraries we will make us of in this tutorial so we are going to add all of them at once.

Now, open your project level build.gradle and add the code below.

buildscript {
    repositories {
    dependencies {
        classpath ''
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
allprojects {
    repositories {
task clean(type: Delete) {
    delete rootProject.buildDir

Also, open the module level build.gradle and add the code below.

apply plugin: ''
apply plugin: ''
android {
    compileSdkVersion 25
    buildToolsVersion "24.0.1"
    defaultConfig {
        applicationId "com.inducesmile.androiddagger2example"
        minSdkVersion 14
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner ""
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), ''
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('', {
        exclude group: '', module: 'support-annotations'
    compile ''
    compile ''
    compile 'com.mcxiaoke.volley:library:1.0.19'
    apt ''
    compile ''
    provided 'javax.annotation:jsr250-api:1.0'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.squareup.okhttp3:okhttp:3.2.0'
    compile 'com.squareup.okio:okio:1.7.0'
    compile ''
    compile 'com.squareup.retrofit2:converter-gson:2.0.1'
    compile ''
    compile 'com.github.bumptech.glide:glide:3.7.0'
    testCompile 'junit:junit:4.12'


We are going to update our project strings.xml file located in the values folder inside the res folder. Open the file and add the code below to it.

    <string name="app_name">Android Dagger2 Example</string>
    <string name="someone_like_you">Someone Like You</string>
    <string name="adele">Adele</string>


Open the colors.xml file in the same location as the strings.xml file and add the code below to the file.

<?xml version="1.0" encoding="utf-8"?>
    <color name="colorPrimary">#63697a</color>
    <color name="colorPrimaryDark">#3c4357</color>
    <color name="colorAccent">#5E433C</color>
    <color name="colorWhite">#ffffff</color>
    <color name="colorHighlight">#DDD2CF</color>

Create Package Folder

To separate some of the classes in their own folder is a way to make searching for a file easier as the project grows. Although, in big project, we might see yourself wrapping features in separate folders rather than related files.

We are going to create three package folders – adapter, dagger and entities as seen in the picture below.


Lets create layout file for our app UI


Open the activity_main.xml file that was created by us. If you do not select default activity creation, you can create a new activity class and name it

In the main layout file, we are going to add a RecyclerView widget. This layout is simple and easy to understands.

Open the activity_main.xml and add the code below.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""
        android:scrollbars="none" />


Create a new layout file in the layout folder inside the res folder. Name this layout file song_layout.xml or anything you wish. This will represent the UI of each list item of the recyclerview widget we create above.

Open this layout file and add the code below.

<?xml version="1.0" encoding="utf-8"?>
< xmlns:android=""
    <LinearLayout xmlns:android=""

Create Adapter for the RecyclerView

The Recyclerview widget in android uses adapter to bind data to its item list. Create an adapter class that will inherit from RecyclerView.Adapter.

Right click on the adapter package folder and click on new java class. Name the class SongAdapter.

Open the file and add the code below to the file

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.inducesmile.androiddagger2example.R;
import com.inducesmile.androiddagger2example.entities.Helper;
import com.inducesmile.androiddagger2example.entities.Songs;
import java.util.List;
public class SongAdapter extends RecyclerView.Adapter<SongViewHolder>{
    private Context context;
    private List<Songs> allSongs;
    public SongAdapter(Context context, List<Songs> allSongs) {
        this.context = context;
        this.allSongs = allSongs;
    public SongViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.songs_layout, parent, false);
        return new SongViewHolder(view);
    public void onBindViewHolder(SongViewHolder holder, int position) {
        Songs mSong = allSongs.get(position);
        String imagePath = Helper.URL + "images/" + mSong.getSongImage();
    public int getItemCount() {
        return allSongs.size();

Create a ViewHolder Class for the Adapter Class

Create a new java class file as in above but this time name the file

Open the file and add the code below.

import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.inducesmile.androiddagger2example.R;
public class SongViewHolder extends RecyclerView.ViewHolder{
    public TextView songTitle;
    public TextView songAuthor;
    public ImageView songImage;
    public SongViewHolder(View itemView, TextView songTitle, TextView songAuthor, ImageView songImage) {
        this.songTitle = songTitle;
        this.songAuthor = songAuthor;
        this.songImage = songImage;
    public SongViewHolder(View itemView) {
        songTitle = (TextView)itemView.findViewById(;
        songAuthor = (TextView)itemView.findViewById(;
        songImage = (ImageView)itemView.findViewById(;

We will leave the MainActivity class for now and when we have setup Dagger 2 then, we will come back to it.

Dagger 2 Dependency Injection

Dagger 2 was built on the standard javax.inject annotations. As stated before, Dagger 2 used code generation for dependency injection while most other android dependency injection libraries make use of reflection.

There are many annotation words that are used Dagger 2 but the most common ones are

@Module – is used to annotate the class that provides the dependencies

@Provides – is a method inside the @Module class that returns an instance of a dependency

@Component – it is a bridge the connects the modules and uses the selected module for dependency injection

@Inject – used to inject dependencies. The @inject annotation can be used on a constructor, field or method.

Create a Module for Dependencies

Create a new class inside the dagger folder and name it We are going to add the Module annotation to this class and also @Provides for the dependencies we need.

Since we are interested on Retrofit class and the Retrofit class has a dependency class Gson, we are going to use two @provide annotations for the two classes.

Open the class and add the code below

import javax.inject.Singleton;
import dagger.Module;
import dagger.Provides;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class NetworksModule {
    private String urlPath;
    public NetworksModule(String urlPath) {
        this.urlPath = urlPath;
    public Gson provideGson(){
        GsonBuilder builder = new GsonBuilder();
        return builder.create();
    public Retrofit provideRetrofit(Gson gson){
        Retrofit retrofit = new Retrofit.Builder()
        return retrofit;

Now we are going to create a Component class. The Component is an interface which Dagger 2 uses to generate code. Dagger 2 add a Dagger prefix to the component interface name. The methods created in the interface are made available to the generated class by Dagger.

Create a new interface file and name it NetworkComponent. Add the component annotation and also specify the Module that the component will use.

Open the file and add the code below to the file.

import com.inducesmile.androiddagger2example.MainActivity;
import javax.inject.Singleton;
import dagger.Component;
@Component(modules = {NetworksModule.class})
public interface NetworkComponent {
    public void inject(MainActivity activity);

You can see from the code above that we have added an inject method and the MainActivity class is passed as a parameter. This will make it possible to inject the Retrofit object in the MainActivity class.

In other to make the component available application wide, we will initialize the component in a custom application class. This will keep the instance of the created graph throughout the application lifecycle.

Create a custom application class that will extends the default Application class. Open the file and add the code below to it.

import com.inducesmile.androiddagger2example.entities.Helper;
public class CustomApplication extends Application{
    private NetworkComponent networkComponent;
    public void onCreate() {
        networkComponent = DaggerNetworkComponent.builder()
                .networksModule(new NetworksModule(Helper.URL))
    public NetworkComponent getNetworkComponent(){
        return networkComponent;

Create a Retrofit Interface

We are going to create an Interface class which the Retrofit fit uses to map its network call.

@GET annotation is used to indicate that it is a GET request,

Create a new interface file and name it Open the file and add the code below.

import java.util.List;
import retrofit2.Call;
import retrofit2.http.GET;
public interface RetrofitNetworkInterface {
    Call<List<Songs>> allSongs();

In the MainActivity class, we are going to use the field inject to inject the Retrofit object to the MainActivity class.

Retrofit retrofit;

In the onCreate() method of the Activity class, we will get the instance of the CustomApplication class the call the getNetworkComponent() and inject method. The Activity reference is passed as a parameter to the inject() method.


This is where the whole magic of injection happens.

We will go ahead to use the instance of the retrofit to create a class from the interface.

Open the MainActivity class and add the code below.

import android.os.Bundle;
import android.util.Log;
import com.inducesmile.androiddagger2example.adapter.SongAdapter;
import com.inducesmile.androiddagger2example.dagger.CustomApplication;
import com.inducesmile.androiddagger2example.dagger.RetrofitNetworkInterface;
import com.inducesmile.androiddagger2example.entities.Songs;
import java.util.List;
import javax.inject.Inject;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
public class MainActivity extends AppCompatActivity {
    private static final String TAG = MainActivity.class.getSimpleName();
    private RecyclerView gridRecycler;
    Retrofit retrofit;
    protected void onCreate(Bundle savedInstanceState) {
        gridRecycler = (RecyclerView)findViewById(;
        GridLayoutManager mGrid = new GridLayoutManager(MainActivity.this, 2);
        RetrofitNetworkInterface mService = retrofit.create(RetrofitNetworkInterface.class);
        Call<List<Songs>> mSong = mService.allSongs();
        mSong.enqueue(new Callback<List<Songs>>() {
            public void onResponse(Call<List<Songs>> call, Response<List<Songs>> response) {
                Log.d(TAG, "Result " + response.body().size());
                SongAdapter mAdapter = new SongAdapter(MainActivity.this, response.body());
            public void onFailure(Call<List<Songs>> call, Throwable t) {
                Log.d(TAG, "Display error code " + t.toString());

Entities Package Folder

Create the following classes in the entities folder and add the codes associated to each.

public class Songs {
    private String songTitle;
    private String songAuthor;
    private String songImage;
    public Songs(String songTitle, String songAuthor, String songImage) {
        this.songTitle = songTitle;
        this.songAuthor = songAuthor;
        this.songImage = songImage;
    public String getSongTitle() {
        return songTitle;
    public String getSongAuthor() {
        return songAuthor;
    public String getSongImage() {
        return songImage;

public class Helper {
    public static String URL = "";

Create Remote Web App and Database

Since we are fetching our data from a remote MYSQL database, we are going to create a simple wen app that will connect to our database, fetch the stored data and make it available to our client android app.

Create a new folder in your server root and name it dagger. Add the following php pages inside the folder.



define("DB_HOST", "localhost");

define("DB_USER", "songs");

define("DB_PASSWORD", "songs");

define("DB_NAME", "songs");




include_once 'config.php';

class database{

private $connect;

public function __construct(){

$this->connect = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

if (mysqli_connect_errno($this->connect))


echo "Failed to connect to MySQL: " . mysqli_connect_error();



public function getDb(){

return $this->connect;


public function getAllSongs(){

$com = new database();

$Song = array();

$Songs = array();

$sql = "select * from songs";

$result = mysqli_query($com->getDb(), $sql);

$rows = mysqli_num_rows($result);

if($rows > 0){

while ($row = $result->fetch_assoc()) {

$Song['id'] = $row['id'];

$Song['songTitle'] = $row['songTitle'];

$Song['songAuthor'] = $row['songAuthor'];

$Song['songImage'] = $row['songImage'];

$Songs[] = $Song;


echo json_encode($Songs, JSON_PRETTY_PRINT);






include_once 'database.php';

$database = new database();



Images folder

Inside the dagger folder, create another folder and name it images. this is where you will store all the images that corresponds to each row in the database.

Create Database Table

The application uses only one table in the database to store its data. You create recreate the table with the sql query below.



`songTitle` varchar(100) NOT NULL,

`songAuthor` varchar(50) NOT NULL,

`songImage` varchar(200) NOT NULL,



In conclusion

This is a simple example on how to use Dagger 2 as Dependency Injection Library in your application. This tutorial does not in another cover most of the features in Dagger 2 but it will afford your a foundation to run from.

If you have any question or suggestion about Dagger 2 kindly leave a message in the comment section below.

This brings us to the end of this tutorial. I hope that you have learn something. Run your app and see for yourself.

You can download the code for this tutorial below. If you are having hard time downloading the tutorial, kindly contact me.

Remember to subscribe with your email address to be among the first to receive my new android blog post once it is published.

One Response

  1. Avatar

Add a Comment