Deleting entire DB
I am currently using objectbox via dependency injection within my android app. It works fine however i need to re-initialise my DI and so i need to destroy the boxStore before. This is because i initialise the box via DI and if i do not destroy the current BoxStore I cannot create a new one.
I have tried calling deleteAllFiles however i am getting an error.
BoxStore.deleteAllFiles(context, (BoxStoreBuilder.DEFAULT_NAME))
BoxStore.deleteAllFiles(context, null)
I am getting the error message:
java.lang.IllegalStateException: Cannot delete files: store is still open
this is on the line of code mentioned above. Any suggestions would be very helpful
@ntohill95 Close the store first before deleting. I created a delete database in my ObjectBox singleton that looks something like this:
object ObjectBox {
lateinit var boxStore: BoxStore
fun init(context: Context) {
try {
boxStore = MyObjectBox.builder().androidContext(context.applicationContext).build()
} catch (e: LinkageError) {
Toasty.error(context, "Please download the app from the PlayStore").show()
Intent(Intent.ACTION_MAIN).apply {
addCategory( Intent.CATEGORY_HOME )
flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
startActivity(context,this, null)
}
}
if (BuildConfig.DEBUG) {
Timber.d( "Using ObjectBox ${BoxStore.getVersion()} (${BoxStore.getVersionNative()})")
}
}
fun deleteDatabase(context: Context){
if (!boxStore.isClosed)
boxStore.close()
boxStore.deleteAllFiles()
init(context) //initialise objectBox again
}
}
You can then call it from from your code like so
ObjectBox.deleteDatabase(context)
Thanks for the response! I thought I would have been able to call BoxStore.close() however as I was using DI to keep the same instance of my objectBox for each of my boxes this was not possible. I resolved it by creating a function within my BoxManager that would close and delete each box.
fun closeAll(){ firstBox.box.close() secondBox.box.closer() ...... firstBox.box.deleteAllFiles() secondBox.box.deleteAllFiles() ..... }
@ntohill95 Note that ObjectBox caches the Box classes for you, so there should be no need to create your own singletons. Just always call boxStore.boxFor().
Also note you could just call boxStore.closeThreadResources().
Closing as this appears to be resolved. ✅ Feel free to re-open with more information or create a new issue.