delete-fileandroid-roomsqliteopenhelper

How do I delete the file of an Android Room database?


I have implemented a room database which is distributed from a resource file using SQLiteAssetHelper the first time the app is started.

The database contains game status data so if the Player wants to start all over again, I want to copy again the database file from the resource and overwrite the "local/internal" file.

So my idea was to delete the interal db-file so that SQLiteAssetHelper will copy the Initial database from the resource again.

Thank you!

Kev


Solution

  • Here's a working example:

    public static void deleteDatabaseFile(Context context, String databaseName) {
        File databases = new File(context.getApplicationInfo().dataDir + "/databases");
        File db = new File(databases, databaseName);
        if (db.delete())
            System.out.println("Database deleted");
        else
            System.out.println("Failed to delete database");
    
        File journal = new File(databases, databaseName + "-journal");
        if (journal.exists()) {
            if (journal.delete())
                System.out.println("Database journal deleted");
            else
                System.out.println("Failed to delete database journal");
        }
    }
    

    but honestly I don't think it will be safe nor reliable to delete database in runtime. You would have to ensure nothing is using it and there aren't any open connections with the database.