Dagger2 - null instead of the entered object

To make things simple, suppose I want to inject an EmailValidator from apache validators into my activity:

public class MainActivity extends FragmentActivity { @Inject EmailValidator emailValidator; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } 

I have a MainModule class:

 @Module public class MainModule { @Provides public EmailValidator providesEmailValidator() { return EmailValidator.getInstance(); } } 

and MainComponent interface:

 @Singleton @Component(modules = MainModule.class) public interface MainComponent { EmailValidator getEmailValidator(); } 

When I try to use my validator in action, I get a nullpointer exception:

 java.lang.NullPointerException: Attempt to invoke virtual method 'boolean org.apache.commons.validator.routines.EmailValidator.isValid(java.lang.String)' on a null object reference 

Obviously I'm missing something. I know that a dagger creates a component implementation for me. Should I use it? How?

If I do the following in my onCreate method:

  emailValidator = Dagger_MainComponent.create().getEmailValidator(); 

then everything works fine.

But I want to be able to use the @ Inject annotation anywhere (probably on a setter / constructor instead of a field).

What am I missing?

I did something similar with dagger1, and it worked. Of course, I needed to call ObjecGraph.inject(this) in action. What is the equivalent of a dagger?

EDIT:

Ok, so I found a solution. If anyone has such a problem, there are some snippets:

1) I created an application class:

 public class EmailSenderApplication extends Application { private MainComponent component; @Override public void onCreate() { super.onCreate(); component = Dagger_MainComponent .create(); component.inject(this); } public MainComponent component() { return component; } } 

2) In AndroidManifest.xml:

 <application android:name=".EmailSenderApplication" ... 

3) And finally, in the activity class, where I want to add some components, these two ugly features:

 component = ((EmailSenderApplication) getApplication()).component(); component.inject(this); 
+8
android dagger-2
source share
1 answer

It looks like you need to create your component like this:

 component = Dagger_ MainComponent.builder() .mainModule(new MainModule()) .build(); 

Typically, you do this in the onCreate method of your application this way .

One good resource that can help you is with sample applications in the Dagger 2 repository .

I also found this PR useful, from the proposed update for the sample application Jake Wharton u2020 (from the chief engineer of Dagger 2). It gives a good overview of the changes you need to make when moving from a dagger 1 to 2, and it seems that it also points to people .

+9
source share

All Articles