【发布时间】:2023-03-09 23:05:01
【问题描述】:
我在 Android MVVM 项目中使用 Dagger 和 ObjectBox
我尝试提供 BoxStore 的单例以及表 Rfid、体重、健康 和我的 AppDBH 类
当我将 AppDBH 添加到 AppModule 并尝试注入时,应用程序崩溃。
原因:io.objectbox.exception.DbException:另一个 BoxStore 仍为此目录打开:/data/data/com.sarveen.framework.forceplate/files/objectbox/objectbox。提示:对于大多数应用程序,建议在应用程序的生命周期内保留 BoxStore。3
这里是 AppModule 类:
@Module
public class AppModule {
@Provides
@Singleton
AppDBH provideAppDBH(Box<Rfid> rfidBox, Box<Weight> weightBox, Box<Health> healthBox) {
return new AppDBH(rfidBox, weightBox, healthBox);
}
@Provides
@Singleton
Box<Rfid> provideBoxRfid(Context context) {
return provideBoxStore(context).boxFor(Rfid.class);
}
@Provides
@Singleton
Box<Health> provideBoxHealth(Context context) {
return provideBoxStore(context).boxFor(Health.class);
}
@Provides
@Singleton
Box<Weight> provideBoxWeight(Context context) {
return provideBoxStore(context).boxFor(Weight.class);
}
@Provides
@Singleton
BoxStore provideBoxStore(Context context) {
return MyObjectBox.builder()
.androidContext(context)
.build();
}
}
这是 AppDBH 类:
@Singleton
public class AppDBH implements DBH{
public AppDBH(Box<Rfid> rfidBox, Box<Weight> weightBox, Box<Health> healthBox) {
this.rfidBox = rfidBox;
this.weightBox = weightBox;
this.healthBox = healthBox;
}
private final String TAG = "BOX_TAG";
private Box<Rfid> rfidBox;
private Box<Weight> weightBox;
private Box<Health> healthBox;
@Override
public List<Rfid> getAllRfids() {
return rfidBox.getAll();
}
@Override
public List<Weight> getAllWeights() {
return weightBox.getAll();
}
@Override
public List<Health> getAllHealths() {
return healthBox.getAll();
}
@Override
public long insertRfid(Rfid rfid) {
return rfidBox.put(rfid);
}
@Override
public long insertWeight(Weight weight) {
return weightBox.put(weight);
}
@Override
public long insertHealth(Health health) {
return healthBox.put(health);
}
}
【问题讨论】:
-
欢迎来到 Dagger。我建议在创建 BoxStore 时设置断点并查看日志消息以了解其他 ObjectBox 创建。
标签: android mvvm objectbox dagger