由于需要修改源码,所以无法再通过compile 'de.greenrobot:greendao:2.0.0'来引入依赖库,下载GreenDao代码:
git clone https://github.com/greenrobot/greenDAO.git
只需要DaoCore部分即可,并且可以删除de.greenrobot.dao.test包和de.greenrobot.dao.InternalUnitTestDaoAccess.java
主要需要做如下修改:
1. android.database.sqlite.SQLiteDatabase 改为: net.sqlcipher.database.SQLiteDatabase
2. android.database.sqlite.SQLiteStatement 改为: net.sqlcipher.database.SQLiteStatement
3. android.database.DatabaseUtils 改为: net.sqlcipher.DatabaseUtils
4. de.greenrobot.dao.internal.FastCursor增加实现方法:
@Override
public void setExtras(Bundle extras) {
}
由于修改量不大,对于DaoGenerator部分暂时没有研究,以后有时间再做研究,本人目前使用的是AndroidAnnotations还没有升级到butterknife,所以本次还是暂时使用它。
项目的build.gradle修改如下:
classpath 'com.android.tools.build:gradle:1.5.0'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' // 新增
在module的buid.gradle修改内容如下:
apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt' // 新增
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "org.penguin.study.android.sqlciphertest"
minSdkVersion 14
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
packagingOptions {
exclude 'META-INF/LICENSE'
exclude 'META-INF/NOTICE'
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.*'])
compile 'com.android.support:appcompat-v7:23.1.1'
apt 'org.androidannotations:androidannotations:3.3.2'
compile 'org.androidannotations:androidannotations-api:3.3.2'
}
apt {
arguments {
resourcePackageName android.defaultConfig.applicationId
androidManifestFile variant.outputs[0]?.processResources?.manifestFile
}
}
创建Dao工具类:
package org.penguin.study.android.sqlciphertest.util;
import android.content.Context;
import net.sqlcipher.database.SQLiteDatabase;
import org.androidannotations.annotations.EBean;
import org.androidannotations.annotations.RootContext;
import org.penguin.study.android.sqlciphertest.dao.BookDao;
import org.penguin.study.android.sqlciphertest.dao.DaoMaster;
import org.penguin.study.android.sqlciphertest.dao.DaoSession;
@EBean(scope = EBean.Scope.Singleton)
public class DAOBean {
static final String TAG = DAOBean.class.getSimpleName();
public static final String DATABASE_NAME = "demo-db";
static final String secretKey = "Your Secret Key";
private SQLiteDatabase db;
private DaoMaster daoMaster;
private DaoSession daoSession;
private BookDao bookDao;
@RootContext
Context context;
public DaoSession getDaoSession() {
if (daoSession == null) {
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, DATABASE_NAME, null);
db = helper.getWritableDatabase(secretKey);
daoMaster = new DaoMaster(db);
daoSession = daoMaster.newSession();
}
return daoSession;
}
public BookDao getBookDao() {
if (bookDao == null) {
bookDao = getDaoSession().getBookDao();
}
return bookDao;
}
}
具体使用:
package org.penguin.study.android.sqlciphertest;