In our last blog, we created a simple example of Dagger2. We will explore Dagger2 in more detail. We will learn, how we can add more than one module in the Dagger component?

Let’s start the project. First, include the 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'

Step-1
Create a student model class with only one property, you can add more than one properties.

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;
    }
}

Step-2
Create a module of Student and simply provide student model with @provides annotation.

package com.becody.daggerexample;

import javax.inject.Inject;

import dagger.Module;
import dagger.Provides;

/**
 * Created by Becody on 05,10,2019
 */
@Module
public class StudentModule {

    @Provides
     StudentModel providesStudentModel() {
        return new StudentModel();
    }
}

Now our 1st module is ready. Now we will create the 2nd module of SharedPreferences.

Step-3
Create a class called PreferenceHelper. Now because we have to SharedPreferences instance in this class, so we will inject SharedPreferences in PreferenceHelper constructor.

package com.becody.daggerexample;

import android.content.SharedPreferences;

import javax.inject.Inject;

/**
 * Created by Becody.com on 07,10,2019
 */
public class PreferenceHelper {


    SharedPreferences sharedPreferences;


    private final String key_name = "key_name";

    @Inject
    public PreferenceHelper(SharedPreferences sharedPreferences){
        this.sharedPreferences = sharedPreferences;
    }

    public void saveFirstName(String name) {
        sharedPreferences.edit().putString(key_name, name).apply();
    }

    public String getFirstName() {
        return sharedPreferences.getString(key_name, "");
    }
}

Step-4
Now we create a 2nd module that will provide SharedPreferences instance using @provides annotation.

package com.becody.daggerexample;

import android.content.Context;
import android.content.SharedPreferences;

import dagger.Module;
import dagger.Provides;

/**
 * Created by becody.com on 07,10,2019
 */

@Module
public class AppSharedPreference {
    private Context _context;

    public AppSharedPreference(Context context) {
        this._context = context;
    }

    @Provides
    SharedPreferences providesSharedPreferences() {
        return _context.getSharedPreferences("cache_name", Context.MODE_PRIVATE);
    }
}

Step-5
Now add these two modules in the component.

package com.becody.daggerexample;

import android.content.SharedPreferences;

import javax.inject.Singleton;

import dagger.Component;

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

    StudentModel getStudentModel();
    PreferenceHelper getPreferenceHelper();

    void inject(MainActivity mainActivity);
}

Now we will use both modules in ActivityMain.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;

    StudentModel studentModel;

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

    }

    public void setUpValues(View v) {
        studentModel.setStudentName("becody.com");
        component.getPreferenceHelper().saveFirstName(studentModel.getStudentName());

    }

    public void getStuValues(View v) {
        Toast.makeText(this, component.getPreferenceHelper().getFirstName(), 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);
    }
}

Thanks for reading the tutorial. Please like our Facebook page for a new and latest tutorial. Join our WhatsApp group for asking any questions about this tutorial. Please subscribe to our Youtube channel for the latest updates and tutorials.

2 Comments

  1. I was recommended this website by way of my cousin. I am now not positive whether this submit is written by way of him as no one else realize such designated about my difficulty. You’re amazing! Thanks!

Write A Comment