房间数据库关闭后如何重新打开

时间:2021-01-15 22:43:50

标签: android database android-studio encryption android-room

我想加密房间的现有数据库。 为此,我使用 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();


你能告诉我关闭数据库后如何重新打开吗。

0 个答案:

没有答案
相关问题