Dagger 03: Injecting via an AppModule using @Provides and @Inject

1. Create a class AppModule to inject stuff at the Application level. Add the AppModule in the modules section. Do not forget.

@Module
public class AppModule {

}

2. In this class you can inject stuff like Retrofit instance or Glide Instance or a Constant class instance into your Activities by using @Provides. To Inject a String that represents a value, add the following code into the AppModule class

   @Provides
    static String someString() {
        return "This is a test string";
    }

3. To use these values inside your Activity using @Inject annotation in front the properties into which you wanna inject these values. 

    private static final String TAG = "AuthActivity";
    
    @Inject
    String injectedString;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_auth);
        Log.d(TAG, "onCreate: " + injectedString);
    }

Comments

Popular posts from this blog

What happened to the blog ?

Why I love to be a programmer ?