I'm trying to use a prepopulated database in my Android project. My pipeline is this:
- I'm creating a new database and processing a large JSON file to populate it (on Android). It takes a lot of time (~15 minutes or so), so I'd like to pack this created database and distribute it with the app.
- I upload the database to Firebase Storage and download it manually on my PC. This database file, when checked with a browser from https://sqlitebrowser.org/, appears correct.
- I add the downloaded database to Assets folder, and copy it over to original database path.
- The database should work at this point, but it doesn't. There's no error message. It appears empty, but the copied file has proper size and everything. Restarting the app doesn't help, and calling new Room.databaseBuilders doesn't help either.
Code:
Database:
@Database(entities = {...}, version = 1)
public abstract class MyDatabase extends RoomDatabase {
public abstract DbDao dbDao();
private static MyDatabase instance = null;
public static MyDatabase getInstance(Context context) {
if (instance == null){
instance =
Room.databaseBuilder(context, MyDatabase.class, "db")
.build();
}
return instance;
}
Uploading:
public void uploadDB(){
String DBPath = mContext.getDatabasePath("db").getAbsolutePath();
File file = new File(DBPath);
StorageReference storageRef = FirebaseStorage.getInstance().getReference().child("db/my_database.db");
BufferedInputStream bis;
try {
bis = new BufferedInputStream(new FileInputStream(file));
} catch (FileNotFoundException e){
e.printStackTrace();
return;
}
storageRef.putStream(bis);
}
Copying:
public void loadDbFromAssets() throws IOException {
InputStream in = mContext.getAssets().open("databases/my_database.db");
String db_path = mContext.getDatabasePath("db").getAbsolutePath();
File out_file = new File(db_path);
if (out_file.exists()){
boolean deleted = out_file.delete();
if (!deleted) {
DebugLog.log("Old DB not deleted!");
return;
}
}
OutputStream out = new FileOutputStream(out_file);
copy(in, out);
File in_file = new File(db_path);
DebugLog.log("Copied file size: " + in_file.length() + "b");
}
public static void copy(InputStream in, OutputStream out) throws IOException{
try {
try {
byte[] buff = new byte[1024];
int len;
while ((len = in.read(buff)) > 0){
out.write(buff, 0, len);
}
} finally {
out.flush();
out.close();
}
} finally {
in.close();
}
}
Am I missing something?