Not sure if this is what you are looking for but in my case just like @M.Yogeshwaran I needed to be able to setup an initial state of the database and work from there so I ended up doing this:
/**
* @param context
*/
public DatabaseService(Context context) {
File dst = context.getDatabasePath(DB_NAME);
dst.delete();
File src = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getPath()+"/database.db");
try {
copy(src,dst);
} catch (IOException e) {
e.printStackTrace();
}
// Init the database singleton
db = Room.databaseBuilder(context, CrediforceDatabase.class, Constants.DB_NAME).build();
}
public static void copy(File src, File dst) throws IOException {
try (InputStream in = new FileInputStream(src)) {
try (OutputStream out = new FileOutputStream(dst)) {
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
}
}
To give a bit more clarity:
- DB_NAME = "database.db"
- For testing purposes, I have the "database.db" that I want to "import" in my downloads folder, later on I will convert this code so instead the device pulls the initial database from the server.
- the dst.delete(); is just to delete the existing database file as I was testing things out (not sure if required)
- This basically translates to: Start the app > Replace the database file > build the database.
- Gotta be careful with the identity_hash in the room_master_table, if this is different from what's supposed to be it's not going to work.
Also, I pulled this idea from this answer:
https://stackoverflow.com/a/50383879/2150472
Hope it helps anyone!
P.S, if what you need is just to be able to see the data and perform CRUD operations you can always use this plugging: https://github.com/amitshekhariitbhu/Android-Debug-Database