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

限于喜欢 提交于 2020-06-12 07:17:19

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/49859778/how-do-i-delete-the-file-of-an-android-room-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!