Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Learn Android Dagger 2.x Framework Dependency Injection - Beginners Guide

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1
    • 0
    • 820
    Comment on it

    Dagger 2 is framework that provides dependency injection. It is based on the JSR which is JAVA SPECIFICATION REQUEST. It is based on annotations and uses code generation to performs its task.

     

    Following are the annotations used by dagger

    • @Component: selected modules are enabled to perform dependency injection.
    • @Inject: To request a dependency in any class.
    • @provides and @module :- dependency provider class or functions.

    Dagger 2 uses generated java code after compilation to access the fields in the modules and not reflection. Therefore private fields can not be used for injection.

     

    Steps to use it in your code :-

    Step 1: Add Dagger compile statement to your gradle file.

     

    compile 'com.google.dagger:dagger:2.8'
    annotationProcessor 'com.google.dagger:dagger-compiler:2.8'
    

     

    Here I am using 2.8 version of dagger you can use the latest at the time you are reading this blog.


     

    Step 2: Create a class and annotate it with module.

     

    let's see an example example:

    @Module
    public class Modules {
    
       private String mBaseUrl;
       private Context context;
    
       // Constructor needs one parameter to instantiate.
       public Modules(String baseUrl, Context context) {
           this.mBaseUrl = baseUrl;
           this.context = context;
       }
    
    
       @Provides
       @Singleton
       AppConstants provideLoginRequest(){
           return new AppConstants();
       }
    
    }
    

     

    Here I have a class named module whose constructor require two params that is base url (String) and context of the app.


     

    Step 3: Create an interface and annotate it with the component and provide the name of modules to be injected.

     

    Lets see an Example.

    @Singleton
    @Component(modules={Modules.class})
    public interface Injector {
       void inject(HomeActivity activity);
    }
    
    

    Here i have a Module class which will be injected to my Home Activity.


     

    Step 4: Now create a java class that extends Application Class and initialize you injector over here.

     

    lets see an example example;

    public class AppInitials extends Application {
    
       /**
        * The Injector.
        */
       Injector injector;
    
       private static AppInitials context;
    
       private String Base_url = " test url";
    
       @Override
       public void onCreate() {
           super.onCreate();
    
           context = this;
    
           injector = DaggerInjector.builder()
                   .modules(new Modules(AppConstants.CUSTOM_VALUE, this))
                   .build();
    
       }
    
       /**
        * Gets injector.
        *
        * @return the injector
        */
       public Injector getInjector() {
           return injector;
       }
    
    
       /**
        * Get context app initials.
        *
        * @return the app initials
        */
       public static AppInitials getContext(){
           return  context;
       }

    Here DaggerInjector.builder() method builds your dependency

    And the public methods here will provide the injector to the requesting classes.


     

    Step 5: Use Annotation Injection to Get Dependency by onCreate Method

     

    Inside your activity or fragment use annotation @inject to get the dependency over there and use it. Also you will have to call the injector method before using any dependency so the best way to do it is at your onCreate method.

    Eg.

     

    @Inject
    AppConstants appConstants;
    
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_home);
       AppInitials.getContext().getInjector().inject(this);
    
       TextView txt_value = findViewById(R.id.txt_value);
    
       txt_value.setText("injected value is " + appConstants.CUSTOM_VALUE);
    }
    

    Here Appconstants is being injected in my homeActivity and getInjector.inject is being called at on create of the activity now when I have all the public methods and fields available to use in my activity.




     

    That's all , You have now successfully integrated dagger2 in your code. Now no more object creations only single object will served throughout the app if you have declared it as singleton in module.


     

    Click here to have a look on working tutorial of the above blog and don’t forget to follow me on github. For Any questions feel free to post in comment section below.

    Happy coding :)

    Learn Android Dagger 2.x Framework Dependency Injection - Beginners Guide

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: