I have my component like
@GithubListActivityScope
@Component(modules = { GithubListActivityModule.class,GlideActivityModule.class })
public interface GithubListActivityComponent {
GithubUserListAdapter githubUserListAdapter ( );
RequestManager requestManager();
LinearLayoutManager linearLayoutManager();
}
And I have a module like this :
@Module
public class GithubListActivityModule {
private final Activity githubListActivity;
public GithubListActivityModule ( Activity activity ) {
this.githubListActivity = activity;
}
@Provides
@GithubListActivityScope
Activity activity ( ) {
return this.githubListActivity;
}
@Provides
@GithubListActivityScope
public LinearLayoutManager linearLayoutManager(Activity activity){
return new LinearLayoutManager ( activity );
}
}
Problem : I have treid to inject LinearLayout manager like this :
@GithubListActivityScope
@Inject
LinearLayoutManager linearLayoutManager;
While my Component is built like this :
githubListActivityComponent = DaggerGithubListActivityComponent.builder ()
.githubListActivityModule ( new GithubListActivityModule ( this ) )
.build ();
my Linear Layout manager does not get instantiated. But when I manually do
linearLayoutManager = githubListActivityComponent.linearLayoutManager ();
It works fine. Where am I going wrong?
Dagger 2 does not inject fields automatically. It can also not inject private fields. If you want to use field injection you have to define a method in your @Component interface which takes the instance into which you want to inject as parameter (From - http://www.vogella.com/tutorials/Dagger/article.html#special-treatment-of-fields-in-dagger)
Suppose you have a fragment or Activity into which you want to inject these dependencies, then do something like this -
Let your Application class be like this -
and your component class be something like this -
Everywhere that I am passing
Activity
, I should pass exactly the same class Name (not its parent) So once edited every parameters and return types that were"Activity"
into"GithubListActivity"
and then addedinside the
component class
then injected
"GithubListActivity"
like this :Then the codes worked for me ..
Lesson :
1. Define inject method and Inject the current Activity
2. Use exactly the same type of object (not the parent ) in this case use "GithubListActivity" instead of just activity.