<p>Here in this tutorial i will explain you what the dependency injection is and why do we need it? I will also let you know why do we use it and what happens when we don&#8217;t use it?We will also learn about how we inject dependency in our android project using dagger2 .</p>
<h3><span style="color: #000080;"><strong><span id="What-is-Dependency-Injection">What is Dependency Injection?</span></strong></span></h3>
<p><strong>The term “Dependency Injection” or in short “DI” is a design pattern ,which is build upon the concept of Inversion of Control. </strong></p>
<ul>
<li><strong>That means a class should get its dependencies from outside. </strong></li>
<li><strong>In more simpler words, we can say class cannot instantiate another class using a new keyword inside it. Instead, you have to supply the object from outside.</strong></li>
</ul>
<p>To understand it in more detail, let’s break the term Dependency Injection in two parts Dependency and Injection.</p>
<p>Get <span style="color: #333399;"><strong>GITHUB</strong></span> code from <span style="color: #0000ff;"><a style="color: #0000ff;" href="https://github.com/arunk7839/AndroidDagger2Example"><strong>Here</strong></a>.</span></p>
<p><span class="embed-youtube" style="text-align:center; display: block;"><amp-youtube data-videoid="0nbf5l35lxE" data-param-rel="1" data-param-showsearch="0" data-param-showinfo="1" data-param-iv_load_policy="1" data-param-fs="1" data-param-hl="en-US" data-param-autohide="2" data-param-wmode="transparent" width="1200" height="675" layout="responsive"><a href="https://www.youtube.com/watch?v=0nbf5l35lxE" placeholder><amp-img src="https://i.ytimg.com/vi/0nbf5l35lxE/hqdefault.jpg" alt="YouTube Poster" layout="fill" object-fit="cover"><noscript><img src="https://i.ytimg.com/vi/0nbf5l35lxE/hqdefault.jpg" loading="lazy" decoding="async" alt="YouTube Poster"></noscript></amp-img></a></amp-youtube></span></p>
<h4><strong><span id="What-is-Dependency" style="color: #000080;">What is Dependency?</span></strong></h4>
<p>Consider the following Java class.</p>
<pre><code>public class Customer {
 
Private Account account;
public Customer()
{
 account = new Account();
}
}</code></pre>
<p>In the above class, we are creating the object of class <span style="color: #008000;"><strong>Account</strong></span> inside the class <span style="color: #008000;"><strong>Customer</strong></span>. So here, we can say that the <span style="color: #008000;"><strong>Customer</strong></span> is dependent on <span style="color: #008000;"><strong>Account </strong></span>object or we can say <span style="color: #008000;"><strong>Account</strong></span> is a dependency for the class <span style="color: #008000;"><strong>Customer</strong></span>.</p>
<h4><strong><span id="What-is-Injection" style="color: #000080;">What is Injection?</span></strong></h4>
<p>As we seen the <span style="color: #008000;"><strong>Customer</strong></span> is Dependent on <span style="color: #008000;"><strong>Account</strong></span>, now how do we get this <span style="color: #008000;"><strong>Account</strong></span> object inside the <span style="color: #008000;"><strong>Customer</strong></span> class .</p>
<p>We can consider the following ways.</p>
<ul>
<li><span style="color: #0000ff;"><strong>Create Account object inside the Customer Constructor or inside the Customer class. </strong></span></li>
</ul>
<pre><code>public class Customer 
{ 
Private Account account;
public Customer() 
{ 
account = new Account(); 
} 
}</code></pre>
<p>Or</p>
<pre><code>public class Customer 
{ 
Private Account account;

account = new Account(); 
 
}</code></pre>
<p>But this is a bad idea because now <span style="color: #008000;"><strong>Customer</strong></span> class get dependent on <span style="color: #008000;"><strong>Account</strong></span> object .</p>
<p>Ideally java class should be as independent from other classes, this increases the possibility of &#8212;&#8211;</p>
<ol>
<li>reusing these classes.</li>
<li>Testing these classes independently from other classes.</li>
</ol>
<ul>
<li><span style="color: #0000ff;"><strong>Instead of using new to instantiate the Account inside Customer&#8217;s constructor we can pass the Account as an argument to the Customer&#8217;s constructor.</strong></span></li>
</ul>
<pre><code>public class Customer { 

private Account account;
public Customer(Account account)
 { 
this.account = account; 
 } 
 }</code></pre>
<p>Doing this makes the class <span style="color: #008000;"><strong>Customer</strong></span> now independent from class <strong><span style="color: #008000;">Account </span></strong>.So this is what we call as <strong><span style="color: #0000ff;">Dependency Injection</span></strong>. Means supplying the dependencies(object) from outside the class instead of creating the object inside the class using new keyword.</p>
<h3><strong><span id="What-is-Dagger-2" style="color: #000080;">What is Dagger 2?</span></strong></h3>
<p><strong>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.</strong></p>
<h3><strong><span id="Working-with-Dagger-2" style="color: #000080;">Understanding Basics of Dagger2</span></strong></h3>
<p>Before moving ahead in our Android Project, let’s understand first the basics of Dagger 2.</p>
<p><span style="color: #0000ff;"><strong>So we have three major things in Dagger.</strong></span></p>
<h5><span id="1-Dependency-Provider" style="color: #000080;"> Dependency Provider</span></h5>
<ul>
<li>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 class which will provide us the objects that are called <strong><span style="color: #008000;">dependencies</span></strong> is called <span style="color: #008000;"><strong>Dependency Provider</strong></span>.</li>
<li>And in <span style="color: #008000;"><strong>dagger2</strong></span> the class that you want to make a Dependency Provider, you need to annotate it with the <span style="color: #008000;"><strong>@Module</strong> </span>annotation.</li>
<li>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 <span style="color: #008000;"><strong>@Provides</strong></span> annotation.</li>
<li><strong><span style="color: #008000;">@Module and @Provides</span></strong>: define classes and methods which provide dependencies</li>
</ul>
<h5><strong><span id="2-Dependency-Consumer" style="color: #000080;"> Dependency Consumer</span></strong></h5>
<ul>
<li>dependency consumer 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 <span style="color: #008000;"><strong>@Inject.</strong></span></li>
</ul>
<h5><span id="3-Component"> <span style="color: #000080;">Component</span></span></h5>
<ul>
<li>Finally, we need some connection between our dependency provider and dependency consumer.<br />
For this, we will create an interface by annotating it with <span style="color: #008000;"><strong>@Component</strong></span>. And rest of the thing will be done by Dagger.</li>
</ul>
<h3><span style="color: #000080;"><strong>Using Dagger2 in android project</strong></span></h3>
<p>In this tutorial my aim is to understand you, how to use <strong><span style="color: #008000;">Dagger2</span></strong> in our project instead of <span style="color: #008000;"><strong>working with retrofit </strong></span>.<a href="https://c1ctech.com/android-retrofit-example/"><span style="color: #0000ff;"><strong>Android retrofit Example</strong></span></a> is my previous post Which i am going to modify here so that i can focus on <strong><span style="color: #008000;">dagger2</span></strong>.You can get source code of <span style="color: #0000ff;"><strong>Android retrofit Example</strong></span> from <a href="https://github.com/arunk7839/RetrofitExample"><span style="color: #00ff00;"><strong>here</strong></span></a>.</p>
<ul>
<li>Firstly go to <strong><span style="color: #008000;">build.gradle</span></strong>(app level) and add the dependency for dagger2 as shown below and <strong><span style="color: #008000;">sync</span></strong> the project.</li>
</ul>
<pre><code><strong><span style="color: #008000;">//dagger2</span></strong>
compile 'com.google.dagger:dagger:2.13'
annotationProcessor 'com.google.dagger:dagger-compiler:2.13'</code></pre>
<h3><strong><span id="Creating-Modules" style="color: #000080;">Creating Modules</span></strong></h3>
<p>For this project, we need two modules. The first one is the<strong> <span style="color: #008000;">AppModule</span></strong>, and the Next one is <strong><span style="color: #008000;">ApiClientModule</span>.</strong></p>
<!-- WP QUADS Content Ad Plugin v. 2.0.98.1 -->
<div class="quads-location quads-ad2" id="quads-ad2" style="float:none;margin:0px;">

</div>

<p><span style="color: #000080;"><strong><span id="App-Module">App Module</span></strong></span></p>
<p>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.</p>
<ul>
<li>Create a new class named <span style="color: #008000;"><strong>AppModule</strong></span> and write the following code.</li>
</ul>
<p><strong><span style="color: #0000ff;">AppModule.java</span></strong></p>
<pre><code>package com.c1ctech.androiddagger2example.module;

import android.app.Application;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;

@Module
public class AppModule {

 private Application mApplication;

 public AppModule(Application mApplication) {
 this.mApplication = mApplication;
 }

 @Provides
 @Singleton
 Application getApplication() {
 return mApplication;
 }

}</code></pre>
<ul>
<li>The above code is straightforward, and we just use a new annotation <span style="color: #008000;"><strong>@Singleton</strong></span>. In dagger, we have this annotation, when we want a Single object.</li>
</ul>
<p><strong><span id="API-Module" style="color: #000080;">ApiClient Module</span></strong></p>
<p>This module will provide us retrofit object which we will use later in our MainActivity to make request.</p>
<ul>
<li> So, create the class named <span style="color: #008000;"><strong>AppClientModule</strong></span> and write the following code.</li>
</ul>
<p><strong><span style="color: #0000ff;">ApiClientModule.java</span></strong></p>
<pre><code>package com.c1ctech.androiddagger2example.module;

import javax.inject.Singleton;

import dagger.Module;
import dagger.Provides;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

@Module
public class ApiClientModule {

 public final String BASE_URL;

 public ApiClientModule(String url) {
 this.BASE_URL = url;
 }

 @Provides
 @Singleton
 Retrofit getClient() {
 return new Retrofit.Builder()
 .baseUrl(BASE_URL)
 .addConverterFactory(GsonConverterFactory.create())
 .build();

 }

}</code></pre>
<p>We have done with the Modules. Now let’s define the Component and then we will inject the objects.</p>
<h3><strong><span id="Building-Component" style="color: #000080;">Building Component</span></strong></h3>
<ul>
<li>Now, we will create the Component.</li>
</ul>
<p><strong><span style="color: #0000ff;">ApiComponent.java</span></strong></p>
<pre><code>package com.c1ctech.androiddagger2example;

import com.c1ctech.androiddagger2example.module.ApiClientModule;
import com.c1ctech.androiddagger2example.module.AppModule;

import javax.inject.Singleton;

import dagger.Component;

@Singleton
@Component(modules = {ApiClientModule.class, AppModule.class})
public interface ApiComponent {

 void inject(MainActivity mainActivity);
}</code></pre>
<ul>
<li>Now create a class named <span style="color: #008000;"><strong>MyApplication</strong></span>. In this class we will build the <strong><span style="color: #008000;">ApiComponent</span></strong>.</li>
</ul>
<p><strong><span style="color: #0000ff;">MyApplication.java</span></strong></p>
<pre><code>package com.c1ctech.androiddagger2example;

import android.app.Application;

import com.c1ctech.androiddagger2example.module.ApiClientModule;
import com.c1ctech.androiddagger2example.module.AppModule;

public class MyApplication extends Application {

 private ApiComponent mApiComponent;

 @Override
 public void onCreate() {
 super.onCreate();

 mApiComponent = DaggerApiComponent.builder()
 .appModule(new AppModule(this))
 .apiClientModule(new ApiClientModule("http://cricapi.com/"))
 .build();
 }

 public ApiComponent getComponent() {
 return mApiComponent;
 }
}</code></pre>
<p><span style="color: #ff0000;"><strong>Before moving ahead Rebuild your project. </strong></span></p>
<ul>
<li>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 <span style="color: #008000;"><strong>AndroidManifest.xml</strong></span> and modify it as shown below.</li>
</ul>
<p><img class="wp-image-720 size-full aligncenter" src="https://c1ctech.com/wp-content/uploads/2018/08/dagger.png" alt="" width="835" height="478" /></p>
<h3><strong><span id="Injecting-Dependency-with-Dagger-2" style="color: #000080;">Injecting Dependency with Dagger 2</span></strong></h3>
<p>Now finally, we can inject the dependency.</p>
<ul>
<li>Come inside <span style="color: #008000;"><strong>MainActivity.java</strong></span> and modify it as below.</li>
</ul>
<p><strong><span style="color: #0000ff;">Mainactivity.Java</span></strong></p>
<pre><code>package com.c1ctech.androiddagger2example;

import android.app.Application;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import com.c1ctech.androiddagger2example.adapter.MatchCalenderAdapter;
import com.c1ctech.androiddagger2example.model.CalenderResponse;
import com.c1ctech.androiddagger2example.model.MatchCalender;

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 {

<strong><span style="color: #008000;">//injecting retrofit and application dependency</span></strong>
 @Inject
 Retrofit retrofit;

 @Inject
 Application application;

 private final static String API_KEY = "ENTER YOUR API KEY";
 private static final String TAG = MainActivity.class.getSimpleName();
 RecyclerView recyclerView;


 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 ((MyApplication) getApplication()).getComponent().inject(this);


 recyclerView = (RecyclerView) findViewById(R.id.match_calender_recycler_view);

 recyclerView.setLayoutManager(new LinearLayoutManager(this));
 recyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));

<span style="color: #008000;"><strong>//Using retrofit</strong> </span>
 ApiInterface apiService = retrofit.create(ApiInterface.class);

 Call<;CalenderResponse>; call = apiService.getMatchCalender(API_KEY);
 call.enqueue(new Callback<;CalenderResponse>;() {
 @Override
 public void onResponse(Call<;CalenderResponse>; call, Response<;CalenderResponse>; response) {
 int statuscode = response.code();
 List<;MatchCalender>; matchlist = response.body().getData();

<strong><span style="color: #008000;">//Using application</span></strong>
 recyclerView.setAdapter(new MatchCalenderAdapter(matchlist, application));

 }

 @Override
 public void onFailure(Call<;CalenderResponse>; call, Throwable t) {
 Log.e(TAG, t.toString());
 }
 });
 }
}</code></pre>
<p>Writing the below line allow the <span style="color: #008000;"><strong>MainActivity</strong></span> to inject or use any of the dependencies of all the modules defined in <strong><span style="color: #008000;">ApiComponent</span></strong>.</p>
<pre><code>((MyApplication) getApplication()).getComponent().inject(this);</code></pre>
<p><span style="color: #0000ff;"><strong>When you run your application it will look like this:</strong></span></p>
<p><img class="alignnone wp-image-1554" src="https://c1ctech.com/wp-content/uploads/2020/02/Screenshot_1580979777.png" alt="Screenshot_1580979777" width="488" height="868" /></p>
<p>It will show the list of matches that will be occur today or later.</p>
<p>I hope that this tutorial will help you in understanding the dagger2.Thank you.

