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

2

8

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

Alkyl answered 16/4, 2018 at 14:27 Comment(0)
M
11

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.

Maas answered 16/4, 2018 at 21:41 Comment(1)
how to do you a close connection before deleting? I am getting "Failed to delete database"Stein
S
8

Instead of deleting database files manually you can use dedicated method

context.deleteDatabase("database_name")
Skell answered 20/10, 2021 at 15:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.