上次提供了GreenDao生成項(xiàng)目Dao的內(nèi)容谤祖,這次主要是Dao的引用兄世,熟悉Dao操作的童鞋可以自行略過了。
一邻薯、添加依賴
兩種方法
1. 通過Android Studio自帶Maven Central搜索添加:
打開【Project Structure】-->【Your ModuleName】-->【Dependencies】-->【Add】-->【Library Dependencies】在Maven Central搜索框中搜索greenDao
裙戏,選擇de.greenrobot:greendao:2.1.0
。
2. 通過直接修改build.gradle
具體步驟請(qǐng)參見上篇文章
二厕诡、調(diào)用生成的Dao類
此處采用官網(wǎng)的例子累榜,具體參見官方Example
- 創(chuàng)建數(shù)據(jù)表
new DaoMaster.DevOpenHelper(this, "notes-db", null)
建立數(shù)據(jù)庫連接
daoMaster = new DaoMaster(db);
daoSession = daoMaster.newSession();
noteDao = daoSession.getNoteDao();-
具體操作
private void addNote() {
String noteText = editText.getText().toString();
editText.setText("");final DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM); String comment = "Added on " + df.format(new Date()); Note note = new Note(null, noteText, comment, new Date()); noteDao.insert(note);//插入數(shù)據(jù)庫 Log.d("DaoExample", "Inserted new note, ID: " + note.getId()); cursor.requery(); }
除了insert
還有update
、delete
方法提供使用灵嫌,查詢的話則用getWritableDatabase()
來獲取SQLiteDatabase
對(duì)象操作壹罚。
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "notes-db", null);
SQLiteDatabase noteDb = helper.getWritableDatabase();
Cursor cursor = noteDb.query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy);//query語法請(qǐng)自行Google or Baidu
三、最后的建議
鑒于架構(gòu)的松耦合寿羞,盡量用自己的類來封裝一下這樣的Dao類猖凛,否則可能導(dǎo)致后期維護(hù)異常艱難。
參考: