ObjectBox IllegalStateException:商店已关闭,重新打开 BoxStore

ObjectBox IllegalStateException: Store is closed, Re-Open BoxStore

我正在使用 ObjectBox 版本 1.5.0

这是从数据库中删除所有数据的方法。

public static void clearAllData(){
    mApp.getBoxStore().close();
    mApp.getBoxStore().deleteAllFiles();
}

我想在用户按下注销按钮时从 ObjectBox 中删除所有数据。上面的方法是删除所有数据,但是当我想添加数据时,我又得到了

IllegalStateException: Store is closed

问题:如何重新打开关闭BoxStore?

ObjectBox中添加数据之前重新调用此行(如果有更好的解决方案,请纠正我)

boxStore = MyObjectBox.builder().androidContext(this).build();

长答案:

ApplicationClass

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();
}

这解决了我的问题。