Dagger error: Can't inject a non-static inner class

2.2k Views Asked by At

I'm trying to implement dependency injection in my app using dagger. I have similar structure to described in "Simpler Android apps with Flow and Mortar"

I have a DayScreen class:

@Layout(R.layout.day)
public class DayScreen extends DateScreen {
    LocalDate date;

    public DayScreen(LocalDate date) { this.date = date; }

    @Override public String getMortarScopeName() { return getClass.getName(); }
    @Override public Object getDaggerModule getModule() { retrun new Module(); }

@dagger.Module(addsTo = UiModule.class, injects = DayView.class, complete = false, library = true)
public class Module {
    @Inject RestService api;
    @Inject DateTimeFormatter formatter;

    @Provides @Named("DayScreenDate") LocalDate provideDate(){
        return date;
    }
}

@Singleton
public class Presenter extends ViewPresenter<DayView> {
    //@Inject RestService api;
    //@Inject DateTimeFormatter formatter;
    RestService api;
    DateTimeFormatter formatter;

    @Inject Presenter( RestService api, DateTimeFormatter formatter){
        this.api = api;
        this.formatter = formatter;
    }

    @Override
    protected void onLoad(Bundle savedInstanceState) {
        super.onLoad(savedInstanceState);
        api.statisticsDay(DayScreen.this.date.format(formatter))
                .observeOn(Schedulers.io())
                .subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        resp -> getView().setData(resp.events),
                        err -> Log.e(TAG, err.getLocalizedMessage()),
                        () -> Log.v(TAG, "day stats received")
                );
    }
}

Here DateScreen is an abstract :

public abstract class DateScreen implements Blueprint {
  protected LocalDate date;

  public DateScreen() { this(LocalDate.now()); }
  public DateScreen(LocalDate date) { this.date = date; }

  public LocalDate getDate() { return date; }
  public void setDate(LocalDate date){ this.date = date; }
}

I tried to inject api and formatter in Module and in Presenter through constructor and trough field injection but it cough the same error error: Can't inject a non-static inner class:...

Does anybody know why does it require static class ? Are there any changes that make article i mention above irrelevant ?

Thanks.

1

There are 1 best solutions below

5
On

Non-static classes require an enclosing instance to be instantiated. This is preventing the DI framework from instantiating them. If you have nested classes, then making them static would be a good idea in any case.

If your nested classes essentially depend on the enclosing instance, then you'll have to refactor to make the classes static and define an explicit constructor taking an instance of the enclosing class.