O
O
Oleg Gamega2016-01-30 18:20:45
Android
Oleg Gamega, 2016-01-30 18:20:45

Dagger 2 inject into ContentProvider?

Hello.
I am using dagger 2, I want to inject SqliteOpenHelper into ContentProvider

@Module
public class ApplicationModule {
    private Application mApp;
    public ApplicationModule(Application app) {
        mApp = app;
    }

    @Provides
    @Singleton
    Context provideContext() {
        return mApp.getApplicationContext();
    }

    @Provides
    @Singleton
    DatabaseHelper provideDatabaseHelper() {
        return new DatabaseHelper(mApp.getApplicationContext());
    }

}

public class App extends Application {
public static App app;
    private  AppComponent mAppComponent;
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("Application", "onCreate ");
        app = this;
        initComponent();

    }


    public static App getInstance(){
        return app;
    }
    ApplicationModule getApplicationModule() {
        return new ApplicationModule(this);
    }

    public  AppComponent getAppComponent(){
        return mAppComponent;
    }

    void initComponent() {
        mAppComponent =  DaggerAppComponent.builder()
                .applicationModule(getApplicationModule())
                .build();
    }
    

}

@Component(modules = {ApplicationModule.class})
@Singleton
public interface AppComponent {
    void inject(FriendsActivity activity);
    void inject(Provider provider);
}

if with for Activity everything is simple
@Inject
    public DatabaseHelper mDatabaseHelper;
  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friends_m);
        ((App) getApplication()).getAppComponent().inject(this);
........

then when I catch npe in the ContentProvider, I didn’t work with dagger before and there are suspicions that somewhere I’m very dumb
public class Provider extends ContentProvider {
    @Inject
    DatabaseHelper databaseHelper;
  @Override
    public boolean onCreate() {

        App.getInstance().getAppComponent().inject(this);
        return false;
    }
.......

thanks in advance

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
LeEnot, 2016-01-30
@gadfi

onCreate()provider is called before the corresponding method in Application. I suppose you can try to move the creation of the component to another Application method, for example, a constructor or attachBaseContext

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question