- Android, Java

How to Use Dagger Library in Android App?

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. What is Dagger Library,Types of Dependency Injections, andHow 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 ProjectTo 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 dependenciesCopy 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 fileNavigate 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        Step 4: Create two new Java Classes Make 2 Classes Engine and Wheel with their Empty Constructors like shown belowJavaimport java.io.*;  class Engine {      public void Engine() {    }}Javaimport java.io.*;  class Wheel {      public void Wheel() {    }}Step 5: Create another Java classCreate 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.Javaimport java.io.*;  class Car {      Engine engine;  Wheel wheel;        public void Car(Engine engine , Wheel wheel) {    this.engine = engine;    this.wheel = wheel  }        public String drive(){    return “Driving…”;  }  }Step 6: Working with the MainActivity.java fileNow in the MainActivity, Declare the TextView and Define itCreate new objects of Wheel and Engine ClassNow create a car object using the wheel and engine objectsSimply use the drive function we made in the Car class for getting the StringGo 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.Javaimport androidx.appcompat.app.AppCompatActivity;import android.os.Bundle;  public class MainActivity extends AppCompatActivity {            TextView text;    Wheel wheel;    Engine engine;    Car car;      @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);                        text = findViewById(R.id.textView);        wheel = new Wheel();        engine = new Engine();        car = new Car(engine, wheel);                          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 InterfaceMake 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.Javaimport java.io.*;  @Componentinterface CarComponent {  Car getCar();}Step 8: Add @Inject annotationAdd @Inject annotation for the constructor of all the classes (Car, Engine, Wheel ).Javaimport java.io.*;  class Car {      Engine engine;  Wheel wheel;        @Inject  public void Car(Engine engine , Wheel wheel) {    this.engine = engine;    this.wheel = wheel  }        public String drive(){    return “Driving…”;  }    }Javaimport java.io.*;  class Wheel {      @Inject   public void Wheel(){          }}Javaimport java.io.*;  class Engine {    @Inject   public void Engine() {    }}Step 9: Rebuild the ProjectDon’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.Javaimport androidx.appcompat.app.AppCompatActivity;  import android.os.Bundle;  public class MainActivity extends AppCompatActivity {          TextView text;    Car car;      @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);                          text = findViewById(R.id.textView);        CarComponent carComponent = DaggerCarComponent.create();        car=carComponent.getCar();          String message = car.driving();        text.setText(message);    }}Output:  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.