Dagger2 Android Example Part-1

Dagger2 is a fast dependency injection framework. An earlier version of Dagger was created by Square but now maintained by Google. If you want to read more about Dagger2, click here to read the description of Dagger2. In this tutorial, we will try to understand Dagger2.

Dagger2 uses annotation to generate code, this generated code is very relatively easy to read, debug and understand. Dagger 2 use following annotations

1- @Module and @Provides

These two annotations define the classes and method which provide dependencies.

2- @Inject

@Inject annotation we use to create the instance of the class. This annotation we can use in constructor, method, and field.

3- @Component

@Component annotation we use to enable selected modules. In @Component, we pass all modules in module parameters.

Let’s make an example of Dagger2 by using these all annotations.

Including following dependencies in your Gradle

  implementation 'com.google.dagger:dagger-android:2.15'
    implementation 'com.google.dagger:dagger-android-support:2.11' // if you use the support libraries
    annotationProcessor 'com.google.dagger:dagger-android-processor:2.11'
    annotationProcessor 'com.google.dagger:dagger-compiler:2.11'

First, we will create a model for students.

package com.becody.daggerexample;

/**
 * Created by Becody.com on 05,10,2019
 */
public class StudentModel {
    private String studentName;

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }
}

Now we will create a module of the student. Before starting the class, we will add annotation of @Module. By adding this annotation, now our module is ready. In a module, we provide the instance of different objects, which wants to include in this module. By using @provides annotation, we will provide instance of an object like this.

package com.becody.daggerexample;

import javax.inject.Inject;

import dagger.Module;
import dagger.Provides;

/**
 * Created by Becody.com on 05,10,2019
 */
@Module
public class StudentModule {
    
    @Provides
     StudentModel providesStudentModel() {
        return new StudentModel();
    }
}

In this example, I am creating only one module for your understanding, in the next example, I will use more than one module. Now we will create an interface and before starting interface, we will add annotation @component. By adding @component annotation, this will be our main component. With @component annotation, we will use another annotation to make it a singleton is @Singleton.

package com.becody.daggerexample;

import javax.inject.Singleton;

import dagger.Component;

/**
 * Created by Rana Aamer Sohail on 05,10,2019
 */
@Singleton
@Component(modules = StudentModule.class)
public interface ActivityMainComponent {
    void inject(MainActivity mainActivity);
}

Now we have two ways to get the student model. The first example is that we will inject the student model from our MainActivity.java.

package com.becody.daggerexample;

import android.os.Bundle;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import javax.inject.Inject;

import dagger.android.support.DaggerAppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private ActivityMainComponent component;

    @Inject
    StudentModel studentModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        component = DaggerActivityMainComponent.builder().build();
        component.inject(this);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

    }

    public void setUpValues(View v) {
        studentModel.setStudentName("becody.com");
    }

    public void getStuValues(View v) {
        if (studentModel.getStudentName() == null)
            return;
        Toast.makeText(this, studentModel.getStudentName(), Toast.LENGTH_LONG).show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

The second way is that we create a getter method of student model in our component like this

package com.becody.daggerexample;

import javax.inject.Singleton;

import dagger.Component;

/**
 * Created by Becody.com on 05,10,2019
 */
@Singleton
@Component(modules = StudentModule.class)
public interface ActivityMainComponent {

    StudentModel getStudentModel();
    void inject(MainActivity mainActivity);
}

Now we don’t need to inject student model from MainActivity.java. Simply build the component and by using component instance, fetch the model of the student by calling the getStudentModel() method.

package com.becody.daggerexample;

import android.os.Bundle;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import javax.inject.Inject;

import dagger.android.support.DaggerAppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private ActivityMainComponent component;

    StudentModel studentModel;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        component = DaggerActivityMainComponent.builder().build();
        studentModel = component.getStudentModel();
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

    }

    public void setUpValues(View v) {
        studentModel.setStudentName("becody.com");
    }

    public void getStuValues(View v) {
        if (studentModel.getStudentName() == null)
            return;
        Toast.makeText(this, studentModel.getStudentName(), Toast.LENGTH_LONG).show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

Now you can see also XML of mainactivity.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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/activity_main">

    <Button
        android:id="@+id/btnSetValue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="112dp"
        android:layout_marginEnd="8dp"
        android:text="Set Values"
        android:onClick="setUpValues"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btnPrintValue"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="152dp"
        android:layout_marginEnd="8dp"
        android:onClick="getStuValues"
        android:text="Print Values"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnSetValue" />
</androidx.constraintlayout.widget.ConstraintLayout>

Thanks for reading the tutorial. Please like our Facebook page for a new and latest tutorial.

Leave a Reply

Your email address will not be published. Required fields are marked *