xRay
xRay

Reputation: 801

MainActivity with Dependency Injection

I would like to simply use dependency injection in my class MainActivity. This is what I have tried:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Scanner scanner;

    public MainActivity(Scanner scanner) {
        this.scanner = scanner;
    }

But it gives me the error

has no zero argument constructor

What I understand from that error is that the method MainActivity() should not have any arguments. But how should it work without any??

Upvotes: 0

Views: 1502

Answers (2)

Gabe Sechan
Gabe Sechan

Reputation: 93542

Constructor based DI won't work on Activities because the Android Framework instantiates them, not the DI framework. As such, you need to use post creation injection rather than constructor based injection. I don't know what DI framework you use, but here's some docs on Dagger that show how to do it https://developer.android.com/training/dependency-injection/dagger-android

Upvotes: 3

Grisgram
Grisgram

Reputation: 3243

This means, you also have to create a constructor with zero arguments.

Please keep in mind, that the system will create the instance for you and android expects an empty constructor.

This is true for the startup activity of your app and for all activities you start through an intent. You receive lifecycle callbacks, like onCreate, onResume, onPause, etc. but you don't instantiate activities like this normally.

Please take a look at the activity lifecycle and how Android handles activities: https://developer.android.com/guide/components/activities/activity-lifecycle

I suggest that you create setters to set up your references and not using a DI constructor.

Upvotes: 1

Related Questions