Skip to content
Related Articles

Related Articles

Improve Article

How to Use Dagger Library in Android App?

  • Difficulty Level : Basic
  • Last Updated : 30 Aug, 2021

When we create a new Android Project, eventually we start accumulating different-different dependencies to get certain functionalities, but over time managing them becomes cumbersome, thus an injection framework like Dagger comes into play. However, setting up an injection service like Dagger requires much amount of boilerplate code and has a very steep learning curve. Originally adding raw dependency/version of Dagger without Android Support is a nightmare.

But….. Then comes Dagger-Android, which changes this game and satisfies everything which raw Dagger lacked, like reduced pre-made (boiler-plate) code, still it wasn’t successful. In this article, we are going to understand the following by building a simple project. 

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

  • What is Dagger Library,
  • Types of Dependency Injections, and
  • How to Use the Constructor Dependency Injection in Android?

We are going to build a very simple app in which we will display text. But we are going to do this by using constructor dependency Injection.

Step By Step Implementation 

Step 1: Create a New Project



To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Add dependencies

Copy the following Dagger dependencies and paste them into your App-level build.gradle file. 

implementation ‘com.google.dagger:dagger:2.38.1’

annotationProcessor ‘com.google.dagger:dagger-compiler:2.38.1’

Keep using the latest dagger version, you can get it from here.

Step 3: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Add a Simple TextView in the activity_main.xml file.



XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30sp"      
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
  
</androidx.constraintlayout.widget.ConstraintLayout>

Step 4: Create two new Java Classes 

Make 2 Classes Engine and Wheel with their Empty Constructors like shown below

Java




import java.io.*;
  
class Engine {
   // Constructor
   public void Engine() { 
   }
}

Java




import java.io.*;
  
class Wheel {
   // Constructor
   public void Wheel() { 
   }
}

Step 5: Create another Java class

  • Create a Car Class whose constructor will be taking 2 objects (Engine and Wheel) as arguments.
  • Create a Function drive(), it will be returning a String. Return a simple string “Driving…” in the drive() function.

Java




import java.io.*;
  
class Car {
    
  Engine engine;
  Wheel wheel;
    
  // Constructor
  public void Car(Engine engine , Wheel wheel) {
    this.engine = engine;
    this.wheel = wheel
  }
    
  // method 
  public String drive(){
    return "Driving...";
  }  
}

Step 6: Working with the MainActivity.java file

Now in the MainActivity, 

  1. Declare the TextView and Define it
  2. Create new objects of Wheel and Engine Class
  3. Now create a car object using the wheel and engine objects
  4. Simply use the drive function we made in the Car class for getting the String

Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

Java






import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
  
public class MainActivity extends AppCompatActivity {
    
    // Declaring
    TextView text;
    Wheel wheel;
    Engine engine;
    Car car;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // Defining
        text = findViewById(R.id.textView);
        wheel = new Wheel();
        engine = new Engine();
        car = new Car(engine, wheel);
          
        // Use the drive method from the car object
        String message = car.drive();
        text.setText(message);
    }
}

What is a Dependency? 

Here Dependency Does not mean the Gradle dependency. The car object cannot be created without an engine and wheel object, so the car is dependent on engine and wheel and hence wheel and Engine are dependencies of Car.

Why Dagger?

For creating a car object whose constructor has arguments, we must pass those arguments (engine and wheel ). while creating the car object. For that, we have to create objects of Wheel and Engine which creates messy boilerplate/reusable code and is a very tedious process. To avoid these we can use Dagger Dependency Injection.

Step 7: Make a CarComponent Interface

Make a CarComponent Interface and add @Component Annotation to it. The @Component annotation just tells the compiler that this interface is going to be the Component for the car object.

Java




import java.io.*;
  
@Component
interface CarComponent {
  Car getCar();
}

Step 8: Add @Inject annotation

Add @Inject annotation for the constructor of all the classes (Car, Engine, Wheel ).

Java






import java.io.*;
  
class Car {
    
  Engine engine;
  Wheel wheel;
    
  // Constructor
  @Inject
  public void Car(Engine engine , Wheel wheel) {
    this.engine = engine;
    this.wheel = wheel
  }
    
  // method 
  public String drive(){
    return "Driving...";
  }
    
}

Java




import java.io.*;
  
class Wheel {
   // Constructor
   @Inject
   public void Wheel(){
       
   }
}

Java




import java.io.*;
  
class Engine {
  // Constructor
  @Inject
   public void Engine() { 
   }
}

Step 9: Rebuild the Project

Don’t forget to Rebuild the project after Step 8

Step 10: Come again in the MainActivity, as we have used Dagger Dependency Injection (just added annotations).  All the boilerplate tedious code is gone. Dagger itself will create a CarComponent class so we don’t have to make Wheel and Engine objects. This way Dagger Dependency Injection makes us work easier removes boilerplate code.

Java




import androidx.appcompat.app.AppCompatActivity;
  
import android.os.Bundle;
  
public class MainActivity extends AppCompatActivity {
  
    // Declaration
    TextView text;
    Car car;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // Defining
        text = findViewById(R.id.textView);
        CarComponent carComponent = DaggerCarComponent.create();
        car=carComponent.getCar();
  
        String message = car.driving();
        text.setText(message);
    }
}

Output: 




My Personal Notes arrow_drop_up
Recommended Articles
Page :