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