我想加密房间的现有数据库。为此,我使用 createFromAsset() 方法创建了数据库并将其关闭。加密后再次尝试重建数据库时,数据库内容为空。
String str = "pass";
char[] pass = str.toCharArray();
//build
AppDatabase db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "dictionary_word32")
.createFromAsset("database/dictionary_word14")
.addMigrations(MIGRATION_1_2)
.addMigrations(MIGRATION_3_4)
.addMigrations(MIGRATION_4_5)
.addMigrations(MIGRATION_5_6)
.allowMainThreadQueries()
.build();
db.close();
//encryption
SQLCipherUtils.State state = SQLCipherUtils.getDatabaseState(getApplicationContext(), "dictionary_word31");
Log.d("TAG", String.valueOf(state));
if (state == SQLCipherUtils.State.UNENCRYPTED) {
try {
SQLCipherUtils.encrypt(getApplicationContext(), "dictionary_word31", pass);
Log.d("TAG", "Successfully encrypted database!");
} catch (IOException e) {
Log.e("TAG", "Failed to encrypt previously unencrypted database!");
e.printStackTrace();
}
}
final byte[] passphrase = SQLiteDatabase.getBytes(pass);
final SupportFactory factory = new SupportFactory(passphrase);
//reopen
db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "dictionary_word32")
.allowMainThreadQueries()
.openHelperFactory(factory)
.build();
即使省略加密,结果也是一样的。
//build
AppDatabase db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "dictionary_word32")
.createFromAsset("database/dictionary_word14")
.addMigrations(MIGRATION_1_2)
.addMigrations(MIGRATION_3_4)
.addMigrations(MIGRATION_4_5)
.addMigrations(MIGRATION_5_6)
.allowMainThreadQueries()
.build();
db.close();
//reopen
db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "dictionary_word32")
.allowMainThreadQueries()
.build();
您能告诉我关闭后如何重新打开数据库吗?