使用:
在你project項目的build.gradle配置以下:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'
}
}java
// 使用數據庫升級輔助GreenDaoUpgradeHelper時添加
allprojects {
repositories {
maven { url "https://jitpack.io" }
}
}android
在你的modules 裏app/build.gradle裏配置以下:git
apply plugin: 'org.greenrobot.greendao'github
dependencies {
compile 'org.greenrobot:greendao:3.2.2'sql
// 使用數據庫加密時添加 compile 'net.zetetic:android-database-sqlcipher:3.5.6' // 使用數據庫升級輔助GreenDaoUpgradeHelper時添加 compile 'com.github.yuweiguocn:GreenDaoUpgradeHelper:v2.0.1'
}數據庫
greendao {
schemaVersion 1
daoPackage 'com.greendao.db
targetGenDir 'src/main/java'
}安全
首先,新建datamodel包,用以包含DaoMaster、DaoSession、bean和beanDao等。br/> 而後新建Area實體類,代碼以下:
@Entity
public class Area {br/>@Id
private String AreaCode;
private String AreaName;
}
最後,Build->Make Module 'app',便可自動生成DaoMaster、DaoSession、Area和AreaDao。此時Area實體類的代碼以下:br/>@Entity
public class Area {br/>@Id
private String AreaCode;
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;
}
}
添加其餘實體類的方法與Area同樣。須要注意的是,不要手動修改DaoMaster、DaoSession、bean和beanDao的代碼,由於每一次編譯項目,都會從新生成一次DaoMaster、DaoSession、bean和beanDao。若是修改的話,就會被覆蓋掉。
爲了便於數據的讀取和添加,新建GreenDaoHelper輔助類,代碼以下:
public class GreenDaoHelper extends Application {
private GreenDaoHelper Instance;
private static DaoMaster daoMaster;
private static DaoSession daoSession;session
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()); //獲取未加密的數據庫 }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; }
}
在讀寫數據庫以前,要添加讀寫權限:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
在MainActivity.java中添加讀寫代碼:
public class MainActivity extends AppCompatActivity {app
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<Area> areas = session.getAreaDao().loadAll(); for (int i = 0,n = areas.size();i<n;++i){ stringBuilder.append("地區編碼:").append(areas.get(i).getAreaCode()) .append(",地區名稱:").append(areas.get(i).getAreaName()).append("\n"); } textview.setText(stringBuilder); }
}
運行結果以下圖所示:maven
修改數據庫文件路徑:
默認狀況下,新建立的數據存儲在data的包名目錄下,設備若是不root的話,是沒法查看SQLite數據庫文件的。而實際應用中,咱們每每須要copy數據庫,或借用第三方工具查閱或編輯數據庫內容。此時咱們能夠經過重寫Context的getDatabasePath(String name)、openOrCreateDatabase(String name, int mode, CursorFactory factory)、openOrCreateDatabase(String name, int mode, CursorFactory factory, DatabaseErrorHandler errorHandler)等三個方法來修改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) { /** * 得到數據庫路徑,若是不存在,則建立對象對象 * * @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";// 數據庫所在目錄 String dbPath = dbDir + "/" + name;// 數據庫路徑 // 判斷目錄是否存在,不存在則建立該目錄 File dirFile = new File(dbDir); if (!dirFile.exists()) dirFile.mkdirs(); // 數據庫文件是否建立成功 boolean isFileCreateSuccess = false; // 判斷文件是否存在,不存在則建立該文件 File dbFile = new File(dbPath); if (!dbFile.exists()) { try { isFileCreateSuccess = dbFile.createNewFile();// 建立文件 } catch (IOException e) { e.printStackTrace(); } } else isFileCreateSuccess = true; // 返回數據庫文件對象 if (isFileCreateSuccess) return dbFile; else return super.getDatabasePath(name); } } /** * 重載這個方法,是用來打開SD卡上的數據庫的,android 2.3及如下會調用這個方法。 * * @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會調用此方法獲取數據庫。 * * @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()); //獲取未加密的數據庫 }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; }
}
版本升級更新
好比須要在實體類加一個字段 或者 改變字段屬性等 就須要版本更新來保存之前的數據了;
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); //更改過的實體類(新增的不用加) 更新UserDao文件 能夠添加多個 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();// 注意:該數據庫鏈接屬於 DaoMaster,因此多個 Session 指的是相同的數據庫鏈接。 mDaoMaster = new DaoMaster(db); mDaoSession = mDaoMaster.newSession();}public DaoSession getDaoSession() {return mDaoSession;}public SQLiteDatabase getDb() {return db;}}