Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 321
Kev Avatar asked Apr 16 '18 14:04

Kev


People also ask

Where are room databases stored Android?

Although Room database file is located in the same partition as internal storage, it is located in different folder: Internal storage resides in files folder. Room database file resides in databases folder.

What is the room database in Android?

What is Room? Room is a persistence library that provides an abstraction layer over the SQLite database to allow a more robust database. With the help of room, we can easily create the database and perform CRUD operations very easily.

How does room database work?

Room autogenerates implementations of your @Database and @Dao annotated classes the first time you compile your code after creating a Room Database. The implementation of UserDatabase and UserDao in the preceding example is generated automatically by the Room annotation processor.


2 Answers

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.

like image 117
Michał Baran Avatar answered Sep 30 '22 06:09

Michał Baran


Instead of deleting database files manually you can use dedicated method

context.deleteDatabase("database_name")
like image 39
KaMyLL Avatar answered Sep 30 '22 07:09

KaMyLL