2

I've deleted the room database but still, I can see the previous rows in my database inspector unless I kill the app manually and reopen it. The scenario is logging out and reopen the login activity. The code snippet:

class MyAppCompatActivity:AppCompatActivity(){
//...
 private fun logOut() {
        MyAppDatabase.getInstance(context).clearAllTables()
        MyAppDatabase.getInstance(context).close()
        deleteDatabase(MyAppDatabase.DATABASE_NAME)
        MyFileUtil.deleteDir(cacheDir)
        MyFileUtil.deleteDir(filesDir)
     }
}
object MyFileUtil{ 
  fun deleteDir(dir: File?): Boolean {
        return if (dir != null && dir.isDirectory) {
            val children = dir.list()
            for (i in children.indices) {
                val success = deleteDir(File(dir, children[i]))
                if (!success) {
                    return false
                }
            }
            dir.delete()
        } else if (dir != null && dir.isFile) {
            dir.delete()
        } else {
            false
        }
    }
}

Does anyone know how to clean my database and quickly reopen my activity again by doing an act like kill the app programmatically?

TinaTT2
  • 366
  • 5
  • 17

2 Answers2

0

Are you sure you are deleting your database file? Those FileUtil APIs make me believe you are not deleting the database folder where Android by default puts the databases.

You can get a hold of the directory via getDatabasePath() or better yet, use deleteDatabase() to delete them using the same 'name' you pass into Room's builder.

Also, be sure to call close() on the database before actually deleting it, otherwise you'll run into trouble.

DanyBoricua
  • 400
  • 1
  • 2
  • 11
  • Thanks, But the FileUtil is written by me, it is a custom class. And I did `deleteDatabase()` , it didn't work. I've updated my question to be more clear with the 'close()' included code. – TinaTT2 Feb 27 '21 at 08:36
0

You could call clearAllTables() from RoomDatabase. That way, Room will delete all rows from it's tables created from Entities.

Source: https://developer.android.com/reference/androidx/room/RoomDatabase#clearAllTables()

This will not reset the counter for primary keys set to auto-increment.

Darryl Bayliss
  • 2,677
  • 2
  • 19
  • 28