-1

Trying to use dagger to create a single instance of my database helper so I can access it easier from the various fragments in my app. Everytime I launch the app though it closes with the following error:

Caused by: java.lang.IllegalStateException: Errors creating object graph:
android.content.Context has no injectable members. Do you want to add an injectable constructor? required by class com.dring.smartcut.Modules.myModule

Here is my Module:

    @Module(
        complete = false,
        injects = {
            BaseApplication.class,
            MainActivity.class,
            MainFragment.class,
        }
    )
    public class myModule {

    private Context appContext;

    public myModule(Context context) {
        this.appContext = context;
    }

    @Provides @Singleton Bus provideBus(){
        return new Bus();
    }

    @Provides @Singleton
    RecipeReaderHelper provideRecipeReaderHelper(Context context){
        return new RecipeReaderHelper(context);
    }
}

And the ObjectGraph Creation:

    objectGraph = ObjectGraph.create(new myModule(this));
    objectGraph.inject(this);

Any Help would be appreciated

DRing
  • 6,825
  • 6
  • 29
  • 45

1 Answers1

1

Every fragment should be listed in the injects

injects = {
    BaseApplication.class,
    MainActivity.class,
    MainFragment.class,
    // other fragments
}

In every fragment e.g. in onCreate callback get the ObjectGraph instance then inject given fragment using this

public void onCreate() {
    objectGraph = // obtain ObjectGraph from somewhere e.g. Application
    objectGraph.inject(this);
}

You also have one of the provides method with Context param, so you need to provide also Context or use the local value.

Two possible solutions:

@Provides @Singleton
RecipeReaderHelper provideRecipeReaderHelper() {
    return new RecipeReaderHelper(appContext);
}

or

@Provides
Context provideContext() {
    return appContext;
}

Choose either of those.

tomrozb
  • 25,773
  • 31
  • 101
  • 122
  • I have included every fragment as well, just left them off for length purposes. Also every fragment gets the objectgraph and injects itself as well. When the myModule is just the bus (no sqlitehelper) it works great. When I add the sqlite helper it causes problems – DRing Dec 30 '14 at 22:07
  • @DRing Please check the updated answer. In short you have to provide Context or use the local value in your provide methods. – tomrozb Dec 31 '14 at 08:46
  • I actually was able to figure this out before you updated, but ended up doing what you said, I had the context in the wrong part so it was throwing an error and didnt catch it. Thanks for the help though – DRing Jan 01 '15 at 12:52