So basicly am trying to use dagger to inject a Baz
field into class Foo
, it goes like this
Baz.java
public class Baz {
}
Foo.java
public class Foo {
@Inject Baz baz;
}
but nothing gets injected and baz
still null when i run it, i even tried to write the Baz
empty constructor
and annotate it with @Inject
but it doesn't work either
how dagger work is it able to see all my classes so when i request a class instance he can create one, or am i missing some annotation, or even worse my annotation processor not working. i added those dependencies to my app.gradle
implementation 'com.google.dagger:dagger:2.14.1'
annotationProcessor 'com.google.dagger:dagger-compiler:2.14.1'
If you want to inject something somewhere using Dagger2
, it's essential to have a component
, also you need a place, where you want to have Foo
object (which has a Baz
object itself). In addition to this, you should specify the way, how objects should be created by dagger2
. In your case constructor injection is absolutely OK.
Let's assume, that our component
is TestComponent
and the place, where we want to have Foo
object is MainActivity
, then the code would be something like this:
Baz.java
public class Baz {
@Inject
public Baz() {
}
}
Foo.java
public class Foo {
@Inject
Baz baz;
@Inject
public Foo() {
}
}
TestComponent.java
@Component
public interface TestComponent {
void inject(MainActivity injector);
}
(When you create component
, rebuild the project)
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Inject
Foo foo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DaggerTestComponent.builder().build().inject(this);
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments