我正在尝试在我的Android应用程序中使用dagger2和数据库。我无法使用inject操作访问数据库类。我创建的Database db对象返回null。我是dagger2的新手。谢谢你的帮助。
这是我的数据库类。
public class Database extends SQLiteOpenHelper {
@Inject
public Database(@ApplicationContext Context context) {
super(context, Constants.DATABASE_NAME, null, Constants.DATABASE_VERSION);
}
public void createTables(){..}
public void clearAllTables() {...}
public void dropTable(SQLiteDatabase db, String tableName){
db.execSQL("DROP TABLE IF EXISTS " + tableName);
}
@Override
public void onCreate(SQLiteDatabase db) {.. } .. }
这是我的模块。
@Module abstract public class DatabaseModule {
private Application application;
public DatabaseModule(Application application) {
this.application = application;
}
@Provides
@ApplicationContext
Context provideContext() {
return application;
}}
和组件
@ActivityScope @Subcomponent public interface DatabaseSubcomponent {
@ApplicationContext
Context getContext();
Database getDb(); }
Db对象返回null,如下所示:
@Inject
Database db;
如果你告诉我我犯了什么错误,我将不胜感激。提前谢谢。
答案 0 :(得分:1)
为自己 @ DatabaseScope.java
定义范围注释器@Scope
@Retention(RetentionPolicy.RUNTIME)
public @interface DatabaseScope {
}
然后 DatabaseModule.java 应提供上下文和数据库对象,这是您的模块(在注入数据库对象期间,dagger会自动从对象图中为您注入上下文)
@Module
public class DatabaseModule {
private Application application;
public DatabaseModule(Application application){
this.application = application;
}
@Provides
@DatabaseScope
Context provideContext(){
return application;
}
@Provides
@DatabaseScope
Database provideDatabase(Context context){
return new Database(context);
}
}
然后是 DatabaseComponent.java 。您无需将其注释为子组件
@DatabaseScope
@Component(modules = {DatabaseModule.class})
public interface DatabaseComponent {
void inject(MainActivity mainActivity);
}
然后是 database.java
public class Database extends Object {
public Database(Context context) {
Log.e("database creted"," ");
}
String getmessage(){
return "jenison";
}
}
最后将此注入您的活动
public class MainActivity extends AppCompatActivity {
@Inject
Database db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseComponent component=DaggerDatabaseComponent.builder().databaseModule(new DatabaseModule(getApplication())).build();
component.inject(this);
Log.e("test"," "+db.getmessage());
}
}