Deleting all tables in Android Room Database

Bhanu Pro
1 min readAug 26, 2020
Photo by v2osk on Unsplash

Since google realeased architecture componets, android developers adopting very quickly. and room is one this in architectural components.

first lets see how to delete all databases in sqlite without using room. for this you have to use below code. its works in all conditions.

context.deleteDatabase(DATABASE_NAME)

alternativly you can use this.

val cursor = appDatabase.openHelper.readableDatabase.query("SELECT name FROM sqlite_master WHERE type = \'table\'")
val sqlDatabase = appDatabase.openHelper.writableDatabase
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast) {
val tableName = cursor.getString(0)
val result = sqlDatabase.delete(tableName, null, null)
cursor.moveToNext()
}
}

if you use this code with room, all tables will be deleted, but if you try to insert/update or access any of room databases you will error saying that

Room cannot verify the data integrity. Looks like you've changed schema but forgot to update the version number. 
You can simply fix this by increasing the version number.

So what room is providing for altenative solution is, you can use clearAllTables functions.

appDatabase.clearAllTables()

This is my personal experince. I got a chance to work on big project, and i dont know who tables names and no of tables in advance.and my task is to delete all tables on user logout but i have to keep few tables.

--

--