'Rename and delete Room Database
I am wondering how to rename or delete a Room Database which was instantiated by following code:
AppDatabase db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "database-name").build();
Should I expect a database-name.db file in getApplicationContext().getFilesDir(), which I could then rename or delete? Would this approach be safe?
My current workaround would be to use only one database with multiple tables, emulating multiple databases. I am not sure if this approach scales very well though.
I could not find any answers to this question in the documention. I am not asking how to rename or delete columns or rows.
Solution 1:[1]
To rename a room database you can do the following when getting your database instance :
//Kotlin
fun getDatabase(context: Context) : YourRoomDbClass {
return INSTANCE ?: synchronized(this){
val dbFile = context.applicationContext.getDatabasePath("your_old_db_name.db")
if(dbFile.exists()) dbFile.renameTo(File(dbFile.path + "your_new_db_name.db"))
val instance = Room.databaseBuilder(context.applicationContext, YourRoomDbClass::class.java, "your_new_db_name.db")
.build()
INSTANCE = instance
instance
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Christopher Myers |
