繁体   English   中英

将android.database.sqlite.SQLiteOpenHelper更改为net.sqlcipher.database.SQLiteOpenHelper后未调用onUpgrade和onCreate

[英]onUpgrade and onCreate not being called after changing android.database.sqlite.SQLiteOpenHelper to net.sqlcipher.database.SQLiteOpenHelper

我一直在遵循官方文档 ,以便在我正在开发的应用程序中开始使用SQLCipher Community Edition。 因此,我进行了适当的gradle导入,如下所示:

compile 'net.zetetic:android-database-sqlcipher:3.5.9@aar'

我添加了

@Override
public void onCreate() {
   super.onCreate();
   SQLiteDatabase.loadLibs(this);
}

在MainApplication.java中。 由于我的应用程序已经发布,因此我还在SQLiteOpenHelper类的实例的onUpgrade()方法中放置了一些迁移代码。 不幸的是,尽管我升级了数据库版本号,但我还是打电话: getInstance().getReadableDatabase("testKey"); onUpgrade()和onCreate()方法都不会被调用。 我是否错过了配置中的某些内容?

就像您在以前未加密的数据库中第一次使用密码一样,我建议您强制重新创建数据库。

为此,您只需在DatabaseHelper类中更改数据库名称即可。 更改数据库名称后,设备更新时会触发onCreate(),它将从零开始创建所有数据库。

public class YourDatabaseHelper extends SQLiteOpenHelper {

   public final static String DATABASE_NAME = Constants.DATABASE_NAME; // Change the name to force the database to be created from zero.
   public final static int CURRENT_VERSION = Constants.DATABASE_VERSION_INT;


   public DatabaseHelper(Context context){
       super(context, DATABASE_NAME, null, CURRENT_VERSION);        
   }

   public void onCreate(SQLiteDatabase db){
       // Create all your tables.
   }

   public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
       // No need to do anything in here, because onCreate will be triggered.
   }

}

最后,我找到了解决问题的方法。 我没有在onUpgrade()方法中调用迁移功能,而是在首次查询数据库之前(在打开应用程序之后)添加了迁移代码:

public static void encrypt(Context ctxt, File originalFile, char[] 
passphrase)
throws IOException {
SQLiteDatabase.loadLibs(ctxt);

if (originalFile.exists()) {
  File newFile=
  File.createTempFile("sqlcipherutils", "tmp", ctxt.getCacheDir());
   SQLiteDatabase db=
   SQLiteDatabase.openDatabase(originalFile.getAbsolutePath(), "", null, SQLiteDatabase.OPEN_READWRITE);

   db.rawExecSQL("ATTACH DATABASE '" + newFile.getAbsolutePath()+ "' AS encrypted KEY '"+String.valueOf(passphrase)+"'");
   db.rawExecSQL("SELECT sqlcipher_export('encrypted')");
   db.rawExecSQL("DETACH DATABASE encrypted");

   int version=db.getVersion();

    db.close();

    db=SQLiteDatabase.openDatabase(newFile.getAbsolutePath(), passphrase, null, SQLiteDatabase.OPEN_READWRITE);
    db.setVersion(version);
    db.close();

    originalFile.delete();
    newFile.renameTo(originalFile);
  }
}

我从这个来源获得了解决方案。 感谢作者,无论他是谁!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM