使用:
在你project項(xiàng)目的build.gradle配置如下:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'
}
}
為衡南等地區(qū)用戶提供了全套網(wǎng)頁設(shè)計(jì)制作服務(wù),及衡南網(wǎng)站建設(shè)行業(yè)解決方案。主營業(yè)務(wù)為成都做網(wǎng)站、成都網(wǎng)站制作、衡南網(wǎng)站設(shè)計(jì),以傳統(tǒng)方式定制建設(shè)網(wǎng)站,并提供域名空間備案等一條龍服務(wù),秉承以專業(yè)、用心的態(tài)度為用戶提供真誠的服務(wù)。我們深信只要達(dá)到每一位用戶的要求,就會得到認(rèn)可,從而選擇與我們長期合作。這樣,我們也可以走得更遠(yuǎn)!
// 使用數(shù)據(jù)庫升級輔助GreenDaoUpgradeHelper時(shí)添加
allprojects {
repositories {
maven { url "https://jitpack.io" }
}
}
在你的modules 里app/build.gradle里配置如下:
apply plugin: 'org.greenrobot.greendao'
dependencies {
compile 'org.greenrobot:greendao:3.2.2'
// 使用數(shù)據(jù)庫加密時(shí)添加
compile 'net.zetetic:android-database-sqlcipher:3.5.6'
// 使用數(shù)據(jù)庫升級輔助GreenDaoUpgradeHelper時(shí)添加
compile 'com.github.yuweiguocn:GreenDaoUpgradeHelper:v2.0.1'
}
greendao {
schemaVersion 1
daoPackage 'com.greendao.db
targetGenDir 'src/main/java'
}
? ? ?首先,新建datamodel包,用以包含DaoMaster、DaoSession、bean和beanDao等。?????然后新建Area實(shí)體類,代碼如下:
@Entity
br/>?????然后新建Area實(shí)體類,代碼如下:
@Entity
br/>@Id
private String AreaName;
}
? ? ?最后,Build->Make Module 'app',即可自動(dòng)生成DaoMaster、DaoSession、Area和AreaDao。此時(shí)Area實(shí)體類的代碼如下:@Entity
br/>@Entity
br/>@Id
private String AreaName;
@Generated(hash = 262290694)
public Area(String AreaCode, String AreaName) {
this.AreaCode = AreaCode;
this.AreaName = AreaName;
}
@Generated(hash = 179626505)
public Area() {
}
public String getAreaCode() {
return this.AreaCode;
}
public void setAreaCode(String AreaCode) {
this.AreaCode = AreaCode;
}
public String getAreaName() {
return this.AreaName;
}
public void setAreaName(String AreaName) {
this.AreaName = AreaName;
}
}
? ? ?添加其他實(shí)體類的方法與Area一樣。需要注意的是,不要手動(dòng)修改DaoMaster、DaoSession、bean和beanDao的代碼,因?yàn)槊恳淮尉幾g項(xiàng)目,都會重新生成一次DaoMaster、DaoSession、bean和beanDao。如果修改的話,就會被覆蓋掉。
? ? ?為了便于數(shù)據(jù)的讀取和添加,新建GreenDaoHelper輔助類,代碼如下:
public class GreenDaoHelper extends Application {
private GreenDaoHelper Instance;
private static DaoMaster daoMaster;
private static DaoSession daoSession;
public GreenDaoHelper getInstance() {
if (Instance == null) {
Instance = this;
}
return Instance;
}
/**
* 獲取DaoMaster
*
* @param context
* @return
*/
public static DaoMaster getDaoMaster(Context context) {
if (daoMaster == null) {
try{
DaoMaster.OpenHelper helper = new DaoMaster.DevOpenHelper(context,"test.db",null);
daoMaster = new DaoMaster(helper.getWritableDatabase()); //獲取未加密的數(shù)據(jù)庫
}catch (Exception e){
e.printStackTrace();
}
}
return daoMaster;
}
/**
* 獲取DaoSession對象
*
* @param context
* @return
*/
public static DaoSession getDaoSession(Context context) {
if (daoSession == null) {
if (daoMaster == null) {
getDaoMaster(context);
}
daoSession = daoMaster.newSession();
}
return daoSession;
}
}
??????在讀寫數(shù)據(jù)庫之前,要添加讀寫權(quán)限:
?????在MainActivity.java中添加讀寫代碼:
public class MainActivity extends AppCompatActivity {
private TextView textview;
private DaoSession session;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview=(TextView)findViewById(R.id.textview);
session = GreenDaoHelper.getDaoSession(this);
session.getAreaDao().deleteAll();//清空所有記錄
//添加記錄
Area area = new Area("01","北京");
Area area1 = new Area("02","天津");
session.getAreaDao().insert(area);
session.getAreaDao().insert(area1);
//查詢記錄
StringBuilder stringBuilder = new StringBuilder();
List areas = session.getAreaDao().loadAll();
for (int i = 0,n = areas.size();i
}
? ? ?運(yùn)行結(jié)果如下圖所示:
? ? ?
修改數(shù)據(jù)庫文件路徑:
? ? ?默認(rèn)情況下,新創(chuàng)建的數(shù)據(jù)存儲在data的包名目錄下,設(shè)備如果不root的話,是無法查看SQLite數(shù)據(jù)庫文件的。而實(shí)際應(yīng)用中,我們往往需要copy數(shù)據(jù)庫,或借用第三方工具查閱或編輯數(shù)據(jù)庫內(nèi)容。此時(shí)我們可以通過重寫Context的getDatabasePath(String?name)、openOrCreateDatabase(String?name,?int?mode,?CursorFactory?factory)、openOrCreateDatabase(String?name,?int?mode,?CursorFactory?factory,?DatabaseErrorHandler?errorHandler)等三個(gè)方法來修改SQLite文件的存儲路徑。
public class GreenDaoHelper extends Application {
private GreenDaoHelper Instance;
private static DaoMaster daoMaster;
private static DaoSession daoSession;
public GreenDaoHelper getInstance() {
if (Instance == null) {
Instance = this;
}
return Instance;
}
/**
* 獲取DaoMaster
*
* @param context
* @return
*/
public static DaoMaster getDaoMaster(Context context) {
if (daoMaster == null) {
try{
ContextWrapper wrapper = new ContextWrapper(context) {
/**
* 獲得數(shù)據(jù)庫路徑,如果不存在,則創(chuàng)建對象對象
*
* @param name
*/
@Override
public File getDatabasePath(String name) {
// 判斷是否存在sd卡
boolean sdExist = android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment.getExternalStorageState());
if (!sdExist) {// 如果不存在,
Log.e("SD卡管理:", "SD卡不存在,請加載SD卡");
return null;
} else {// 如果存在
// 獲取sd卡路徑
String dbDir = android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
dbDir += "/Android";// 數(shù)據(jù)庫所在目錄
String dbPath = dbDir + "/" + name;// 數(shù)據(jù)庫路徑
// 判斷目錄是否存在,不存在則創(chuàng)建該目錄
File dirFile = new File(dbDir);
if (!dirFile.exists())
dirFile.mkdirs();
// 數(shù)據(jù)庫文件是否創(chuàng)建成功
boolean isFileCreateSuccess = false;
// 判斷文件是否存在,不存在則創(chuàng)建該文件
File dbFile = new File(dbPath);
if (!dbFile.exists()) {
try {
isFileCreateSuccess = dbFile.createNewFile();// 創(chuàng)建文件
} catch (IOException e) {
e.printStackTrace();
}
} else
isFileCreateSuccess = true;
// 返回?cái)?shù)據(jù)庫文件對象
if (isFileCreateSuccess)
return dbFile;
else
return super.getDatabasePath(name);
}
}
/**
* 重載這個(gè)方法,是用來打開SD卡上的數(shù)據(jù)庫的,android 2.3及以下會調(diào)用這個(gè)方法。
*
* @param name
* @param mode
* @param factory
*/
@Override
public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory) {
return SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), null);
}
/**
* Android 4.0會調(diào)用此方法獲取數(shù)據(jù)庫。
*
* @see android.content.ContextWrapper#openOrCreateDatabase(java.lang.String,
* int,
* android.database.sqlite.SQLiteDatabase.CursorFactory,
* android.database.DatabaseErrorHandler)
* @param name
* @param mode
* @param factory
* @param errorHandler
*/
@Override
public SQLiteDatabase openOrCreateDatabase(String name, int mode, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler) {
return SQLiteDatabase.openOrCreateDatabase(getDatabasePath(name), null);
}
};
DaoMaster.OpenHelper helper = new DaoMaster.DevOpenHelper(wrapper,"test.db",null);
daoMaster = new DaoMaster(helper.getWritableDatabase()); //獲取未加密的數(shù)據(jù)庫
}catch (Exception e){
e.printStackTrace();
}
}
return daoMaster;
}
/**
* 獲取DaoSession對象
*
* @param context
* @return
*/
public static DaoSession getDaoSession(Context context) {
if (daoSession == null) {
if (daoMaster == null) {
getDaoMaster(context);
}
daoSession = daoMaster.newSession();
}
return daoSession;
}
}
?????
版本升級更新
比如需要在實(shí)體類加一個(gè)字段 或者 改變字段屬性等 就需要版本更新來保存以前的數(shù)據(jù)了;
public class Helper extends DaoMaster.OpenHelper{
private static DaoMaster daoMaster;
private static DaoSession daoSession;
public static final String DBNAME = "greendao.db";
public Helper(Context context){
super(context,DBNAME,null);
}
@Override
public void onUpgrade(Database db, int oldVersion, int newVersion) {
super.onUpgrade(db, oldVersion, newVersion);
Log.i("version", oldVersion + "---先前和更新之后的版本---" + newVersion);
if (oldVersion < newVersion) {
Log.i("version", oldVersion + "---先前和更新之后的版本---" + newVersion);
MigrationHelper.getInstance().migrate(db, UserDao.class);
//更改過的實(shí)體類(新增的不用加) 更新UserDao文件 可以添加多個(gè) XXDao.class 文件
// MigrationHelper.getInstance().migrate(db, UserDao.class,XXDao.class);
}
}
/**
* 取得DaoMaster
*
* @param context
* @return
*/
public static DaoMaster getDaoMaster(Context context) {
if (daoMaster == null) {
DaoMaster.OpenHelper helper = new DaoMaster.DevOpenHelper(context,
DBNAME, null);
daoMaster = new DaoMaster(helper.getWritableDatabase());
}
return daoMaster;
}
/**
* 取得DaoSession
*
* @param context
* @return
*/
public static DaoSession getDaoSession(Context context) {
if (daoSession == null) {
if (daoMaster == null) {
daoMaster = getDaoMaster(context);
}
daoSession = daoMaster.newSession();
}
return daoSession;
}
}
public class GreenApplication extends Application {
private DaoMaster.DevOpenHelper mHelper;
//private Helper mHelper;
private SQLiteDatabase db;
private DaoMaster mDaoMaster;
private DaoSession mDaoSession;
public static GreenApplication instances;
@Override public void onCreate() {
super.onCreate();
instances = this;
setDatabase();
}
public static GreenApplication getInstances(){
return instances;
}
/**
//mHelper = new DaoMaster.DevOpenHelper(this, "notes-db", null);
db = mHelper.getWritableDatabase();
// 注意:該數(shù)據(jù)庫連接屬于 DaoMaster,所以多個(gè) Session 指的是相同的數(shù)據(jù)庫連接。
mDaoMaster = new DaoMaster(db);
mDaoSession = mDaoMaster.newSession();
}
public DaoSession getDaoSession() {
return mDaoSession;
}
public SQLiteDatabase getDb() {
return db;
}
}