How to Use Dagger Library in Android App?
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.
- 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:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
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,
- Declare the TextView and Define it
- Create new objects of Wheel and Engine Class
- Now create a car object using the wheel and engine objects
- 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:
Similar Reads
How to Use Balloon Library in Android?
Balloon Library is another popular feature that is commonly used in most Android Apps. You can get to see this feature in most of the shopping and messaging apps. With the help of this feature, you can get a hint about what to do next in any app. In this article, we are going to see how to implement
3 min read
How to Use Morphy Toolbar Library in Android App?
MorphyToolbar is a library that allows us to have a custom toolbar with a title, subtitle, and a picture that further offers the possibility to animate the view between transitions. This library is extremely easy to integrate and offers several customizations. In this article, we will be implementin
4 min read
How to Use COIL Image Loader Library in Android Apps?
COIL is an acronym for Coroutine Image Loader. COIL is one of the famous image loading libraries from URLs in Android. It is a modern library for loading images from the server. This library is used to load images from servers, assets folder as well as from the drawable folder in Android project. Th
4 min read
How to Read QR Code using CAMView Library in Android?
CAMView Library is a simple solution for accessing users' device camera. By using this library we can access users' cameras and use to perform so many functions of the camera such as scanning barcodes that are done by using a built-in ZXing decoding engine. This library contains a set of components
5 min read
How to use Firebase UI Authentication Library in Android?
Firebase UI is a library provided by Firebase for Android apps which makes or so many tasks easy while integrating Firebase in Android. This library provides so many extra features that we can integrate into our Android very easily. In this article, we will take a look at using this library for addi
10 min read
How to Build a Book Library App using Google Books API in Android?
If you are looking for building a book library app and you want to load a huge data of books then for adding this feature, you have to use a simple API which is provided by Google, and of course, it's free. In this article, we will take a look at the implementation of this API in our Android App. Wh
15+ min read
How to Update Data in Realm Database in Android?
In previous articles, we have seen adding and reading data from our realm database in Android. In that article, we were adding course details in our database and reading the data in the form of a list. In this article, we will take a look at updating this data in our android app. What we are going
7 min read
How to Read QR Code using Zxing Library in Android?
Zxing stands for Zebra Crossing, it is one of the most popular open-source API for integrating QR(Quick Response) Code processing. It is a barcode image processing library implemented in Java, with ports to other languages. It has support for the 1D product, 1D industrial, and 2D barcodes. Google us
4 min read
How to Use Dagger in a Multi-Module Project in Android?
We know about the Dagger dependency injection framework and how to use it in a single module project. Dagger is basically used for reducing or completely getting rid of the unnecessary boilerplate code. We have already seen step-by-step usage of the dagger library in android, check it here. But in t
6 min read
What is AndroidX Library in Android?
The Android Extension Library, often known as AndroidX, is the new open-source project that is a significant upgrade to the original Android Support Library and can be used to develop, test, package version, and release libraries within Jetpack. The Android Jetpack libraries are part of the AndroidX
4 min read