0

我正在使用ObjectBox版本1.5.0

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

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

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

IllegalStateException: Store is closed

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

4

1 回答 1

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

这解决了我的问题。

于 2018-08-02T07:50:05.330 回答