android - 房间数据库关闭后如何重新打开
问题描述
我想加密房间的现有数据库。为此,我使用 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();
您能告诉我关闭后如何重新打开数据库吗?
解决方案
推荐阅读
- android - 同时关闭多个 DialogFragment
- sql - 从 Oracle 数据库中的所有表中删除完全重复的行
- java - 计算二维布尔数组中真实语句的数量
- python - Python - Flask - Connexion - Swagger - OpenAPI - 如何隐藏特定的端点规范?
- python - Python-ggplot:将移动平均线添加到绘图中
- stenciljs - 如何在模板 js 中将数据作为对象数组传递?
- python - 在 Docker 中使用多处理进行日志记录
- amazon-web-services - 如何获取订购者日志 | 亚马逊管理的区块链
- .net - 带彩色边框的自定义 GroupBox 控件
- qt - 如何在过渡期间更改委托的属性