I have tried many ways to reset it.
allowBackup
andfullBackupOnly
had been set to false.
.fallbackToDestructiveMigration()
and delete database and cache files directly.
but it doesn't work.
CodePudding user response:
You can use this clear all tables THis deletes all rows from all the tables that are registered to this database as Database.entities().
CodePudding user response:
Simplest way is to uninstall the app, this deletes the database file(s). So rerunning starts from a brand new database.
To use .fallbackToDestructiveMigration()
you have to have to invoke a Migration by increasing the version number but NOT have a Migration for the particular path. You could argue that this doesn't reset the database as the newly created database will have the higher version number.
Using clearAllTables
doesn't entirely reset the database as it will not delete the system tables. Most notably, sqlite_sequence, which is a table that hold the vale of the latest rowid on a per table basis. That is if you have autogenerate = true
in the @PrimaryKey annotation for an field/column that resolves to a column type affinity of INTEGER then AUTOINCREMENT is coded then the sqlite_sequence table will be created (if not already in existence) and store the latest (and therefore highest) value of the said primary key. Thus if you have inserted 100 rows (for example) into a such a table, then after a clearAllTables the 100 will still be stored in the sqlite_sequnce table.
You could also, prior to building the database, delete the database. Here's an example that allows it to be deleted when building :-
@Database(entities = [Customer::class], version = 1)
abstract class CustomerDatabase: RoomDatabase() {
abstract fun customerDao(): CustomerDao
companion object {
private var instance: CustomerDatabase?=null
fun getDatabase(context: Context, resetDatabase: Boolean): CustomerDatabase {
if (resetDatabase && instance == null) {
(context.getDatabasePath("thedatabase.db")).delete()
}
if (instance == null) {
instance = Room.databaseBuilder(context,CustomerDatabase::class.java,"thedatabase.db")
.allowMainThreadQueries()
.build()
}
return instance as CustomerDatabase
}
fun getDatabase(context: Context): CustomerDatabase {
if (instance == null) {
instance = Room.databaseBuilder(context,CustomerDatabase::class.java,"thedatabase.db")
.allowMainThreadQueries()
.build()
}
return instance as CustomerDatabase
}
}
}
- note that in addition to requesting the reset, a check is also made to ensure that an instance of the database hasn't been retrieved.
This would also be more efficient as clearAllTables still incurs processing of the underlying data and the ensuing VACUUM which can be quite resource hungry.