【问题标题】:ObjectBox IllegalStateException: Store is closed, Re-Open BoxStoreObjectBox IllegalStateException: Store is closed, Re-Open BoxStore
【发布时间】:2018-08-02 15:50:05
【问题描述】:
我使用的是ObjectBox版本1.5.0
这是从数据库中删除所有数据的方法。
public static void clearAllData(){
mApp.getBoxStore().close();
mApp.getBoxStore().deleteAllFiles();
}
当用户按下注销按钮时,我想删除 ObjectBox 中的所有数据。上面的方法是删除所有数据,但是当我想添加数据时,我又得到了
IllegalStateException: Store is closed
问题:如何重新打开关闭的BoxStore?
【问题讨论】:
标签:
java
android
objectbox
【解决方案1】:
在ObjectBox 中添加数据之前重新调用此行(如果有更好的解决方案,请纠正我)
boxStore = MyObjectBox.builder().androidContext(this).build();
长答案:
在Application类中
public class BaseApplication extends Application {
public static BaseApplication mInstance;
private BoxStore boxStore;
public static synchronized BaseApplication getInstance() {
return mInstance;
}
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
initializeBoxStore();
}
public BoxStore getBoxStore() {
/* From this method we can get always opened BoxStore */
if (boxStore != null && boxStore.isClosed())
initializeBoxStore();
return boxStore;
}
private void initializeBoxStore() {
boxStore = MyObjectBox.builder().androidContext(this).build();
}
}
在clearAllData方法中
public static void clearAllData(){
BoxStore boxStore = mApp.getBoxStore();
boxStore.close();
boxStore.deleteAllFiles();
}
这解决了我的问题。