如何使用 OrmLite 连接到受密码保护的 SQLite 数据库?

How to connect to Password protected SQLite DB with OrmLite?

我通过以下代码从资产中复制数据库:

    public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
        private static final String DATABASE_NAME = "database.db";
        private static final String DATABASE_PATH = "/data/data/"+BuildConfig.APPLICATION_ID+"/databases/";

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

      private void copyFromAssets(Context context) {
        boolean dbexist = checkdatabase();
        if (!dbexist) {
            File dir = new File(DATABASE_PATH);
                dir.mkdirs();
                InputStream myinput = context.getAssets().open(DATABASE_NAME);
                String outfilename = DATABASE_PATH + DATABASE_NAME;
                Log.i(DatabaseHelper.class.getName(), "DB Path : " + outfilename);
                OutputStream myoutput = new FileOutputStream(outfilename);
                byte[] buffer = new byte[1024];
                int length;
                while ((length = myinput.read(buffer)) > 0) {
                    myoutput.write(buffer, 0, length);
                }
                myoutput.flush();
                myoutput.close();
                myinput.close();
            }
    }
    }

为了获得 Dao,我使用这个:

public Dao<AnyItem, Integer> getDaoAnyItem() throws SQLException {
        if (daoAnyItem == null) {
            daoAnyItem = getDao(AnyItem.class);
        }
        return daoAnyItem;
    }

但是,如果我的数据库受密码保护,如何获取 Dao?

你必须将 SQLCipher 与 OrmLite 一起使用,我会向你推荐 ormlite-sqlcipher

OrmLiteSqliteOpenHelper 有一个接受密码的构造函数,因此将您的超级调用更改为

super(context, DATABASE_NAME, null, DATABASE_VERSION, (File)null, "DB password goes here");

我会从 DatabaseHelper 构造函数中调用 copyFromAssets(context) 并在创建 DatabaseHelper 之前调用它,即应用程序启动时的第一件事