編輯:關於 Android 程式設計
GreenDAO 的工作方式是「用程式碼生成表結構」:你在一個獨立的 Java 專案中描述實體,執行後它會幫你產生對應的 Dao、DaoMaster、DaoSession。因此接入的第一步是把生成產物所在的目錄納入原始碼集。
先在 src/main 下建立一個與 java 同層級的 java-gen 目錄,然後在模組的 build.gradle 中聲明:
// 放在 buildTypes {} 之內
sourceSets {
main {
java.srcDirs = ['src/main/java', 'src/main/java-gen']
}
}
接著添加執行期依賴:
dependencies {
compile 'de.greenrobot:greendao:1.3.7'
}
為了操作方便,建議單獨建一個 Java 專案來跑生成器(該專案需要添加 compile 'de.greenrobot:DaoGenerator:1.3.0'),在 Android 專案中直接依賴生成結果即可。
import de.greenrobot.daogenerator.DaoGenerator;
import de.greenrobot.daogenerator.Entity;
import de.greenrobot.daogenerator.Schema;
public class MyDaoGenerator {
public static void main(String args[]) throws Exception {
// 參數一:數據庫版本號;參數二:生成的 Bean 所在包名
Schema schema = new Schema(1, "greendao.bean");
// DaoMaster、DaoSession、各實體的 Dao 會生成到這個包
schema.setDefaultJavaPackageDao("greendao.dao");
initTable(schema);
try {
// 最後一個參數是輸出目錄,改成你本機的實際路徑
new DaoGenerator().generateAll(schema, "D:\\src\\main\\java-gen");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void initTable(Schema schema) {
Entity table = schema.addEntity("ContentEntity");
// table.setTableName("table"); // 需要自定義表名時再打開
table.addIdProperty().autoincrement(); // 主鍵,自增
table.addStringProperty("status");
table.addLongProperty("version");
table.addStringProperty("tableTypeId");
table.addStringProperty("storeId");
table.addStringProperty("name");
table.addStringProperty("orderby");
}
}
執行 main 方法後,java-gen 目錄下會出現對應檔案,控制台也會打印生成日誌。往後表結構變動,只要回來改 initTable、遞增 schema 版本號再跑一次即可。
DaoMaster 與 DaoSession 屬於進程級的重量級物件,不該反覆創建,放在 Application 裡最合適:
public class BaseApplication extends Application {
public static BaseApplication mInstance;
public static DaoMaster daoMaster;
public static DaoSession daoSession;
@Override
public void onCreate() {
super.onCreate();
if (mInstance == null) {
mInstance = this;
}
}
/** 取得 DaoMaster */
public static DaoMaster getDaoMaster(Context context) {
if (daoMaster == null) {
// 用自定義的 TableOpenHelper 取代官方 DevOpenHelper,以便接管升級邏輯
DaoMaster.OpenHelper helper = new TableOpenHelper(context, "myDb", null);
daoMaster = new DaoMaster(helper.getWritableDatabase());
}
return daoMaster;
}
/** 取得 DaoSession */
public static DaoSession getDaoSession(Context context) {
if (daoSession == null) {
if (daoMaster == null) {
daoMaster = getDaoMaster(context);
}
daoSession = daoMaster.newSession();
}
return daoSession;
}
}
記得在 manifest 的 application 節點上註冊這個類,否則它不會被執行。
官方的 DevOpenHelper 在版本升級時會直接刪表重建,資料全丟。生產環境必須換成自己的 OpenHelper:
public class TableOpenHelper extends DaoMaster.OpenHelper {
public TableOpenHelper(Context context, String name, SQLiteDatabase.CursorFactory factory) {
super(context, name, factory);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch (oldVersion) {
case 1:
// createTable 是靜態方法,可按新結構建表
ContentEntityDao.createTable(db, true);
// 若只是加欄位,也可以直接下 DDL:
// db.execSQL("ALTER TABLE moments ADD audio_path TEXT;");
break;
default:
break;
}
}
}
逐版本分支的寫法在版本數量多起來之後會變得難以維護,如果團隊對這塊要求高,可以參考前面那套「遞歸 + 抽象升級類 + 註解」的組織方式。
Dao 物件本身已經足夠好用,但業務層不該到處拿 DaoSession。封裝一層單例 Facade,好處是調用點整潔,也便於日後替換 ORM:
public class DbService {
private static final String TAG = DbService.class.getSimpleName();
private static DbService instance;
private static Context appContext;
private DaoSession mDaoSession;
private ContentEntityDao contentEntityDao;
private DbService() {
}
/** 單例,順帶持有 applicationContext 避免洩漏 */
public static DbService getInstance(Context context) {
if (instance == null) {
instance = new DbService();
if (appContext == null) {
appContext = context.getApplicationContext();
}
instance.mDaoSession = BaseApplication.getDaoSession(context);
instance.contentEntityDao = instance.mDaoSession.getContentEntityDao();
}
return instance;
}
/** 按主鍵查一條 */
public ContentEntity loadNote(Long id) {
if (!TextUtils.isEmpty(id + "")) {
return contentEntityDao.load(id);
}
return null;
}
/** 取全部 */
public List loadAllNote() {
return contentEntityDao.loadAll();
}
/** 按 id 倒序 */
public List loadAllNoteByOrder() {
return contentEntityDao.queryBuilder().orderDesc(ContentEntityDao.Properties.Id).list();
}
/** 原生 where 條件查詢 */
public List queryNote(String where, String... params) {
return contentEntityDao.queryRaw(where, params);
}
/** 插入或替換 */
public long saveorReplace(ContentEntity user) {
return contentEntityDao.insertOrReplace(user);
}
public long saveNote(ContentEntity user) {
return contentEntityDao.insert(user);
}
/** 批量寫入:務必包在事務裡 */
public void saveNoteLists(final List list) {
if (list == null || list.isEmpty()) {
return;
}
contentEntityDao.getSession().runInTx(new Runnable() {
@Override
public void run() {
for (ContentEntity user : list) {
contentEntityDao.insertOrReplace(user);
}
}
});
}
/** 多條件組合查詢 */
public List queryPerson(WhereCondition arg0, WhereCondition... conditions) {
QueryBuilder qb = contentEntityDao.queryBuilder();
qb.where(arg0, conditions);
return qb.list();
}
public void deleteAllNote() {
contentEntityDao.deleteAll();
}
public void deleteNote(long id) {
contentEntityDao.deleteByKey(id);
Log.i(TAG, "delete");
}
public void deleteNote(ContentEntity user) {
contentEntityDao.delete(user);
}
}
這裡有幾點值得自覺遵守:批量寫入一定要包在 runInTx 中,逐條 insert 的事務開銷會拉出數量級的差距;查詢結果若要在多處使用,記得自己快取,避免在 getView 之類的高頻路徑反覆觸發 SQL;持有 Context 時一律用 getApplicationContext()。
同步類需求通常長這樣:本地有一份快取,服務端下發一份清單,需要按業務主鍵比對後決定新增、保留或刪除。以 tableTypeId 為業務主鍵、status 為 2 表示「服務端已刪除」為例:
public void checkPersonExistAndUpdate(List newList) {
List oldList = loadAllNote();
if (oldList.isEmpty()) {
// 本地無資料:過濾掉已刪除項後全量落庫
Iterator it = newList.iterator();
while (it.hasNext()) {
if (Integer.parseInt(it.next().getStatus()) == 2) {
it.remove();
}
}
saveNoteLists(newList);
return;
}
// 本地有資料:以本地記錄為基準逐條比對
for (ContentEntity local : oldList) {
boolean matched = false;
for (ContentEntity remote : newList) {
if (!local.getTableTypeId().equals(remote.getTableTypeId())) {
continue;
}
matched = true;
if (Integer.parseInt(remote.getStatus()) == 2) {
// 服務端標記刪除 → 移除本地
deleteNote(local);
} else {
// 服務端有效 → 用新資料覆蓋本地
saveorReplace(remote);
}
break;
}
if (!matched && Integer.parseInt(local.getStatus()) == 2) {
// 服務端清單中已不存在且本地標記為刪除,可視需要清理
deleteNote(local);
}
}
}
原始版本在這段邏輯裡用了雙層 for 加多個 return,一旦命中就提前退出整個方法,後續記錄根本不會被處理,而且直接在 foreach 走訪中刪集合元素會引發 ConcurrentModificationException。上面把它改成「以本地為外層、命中即 break 內層」的結構,語義清楚,也不再有跳過記錄的風險。這類同步程式碼建議實作後補一份單元測試,用幾組「新增 / 更新 / 刪除 / 混合」的假資料把分支跑透,比反覆手動調試划算得多。
接入完成後,業務層只需要 DbService.getInstance(this) 就能完成絕大多數增刪改查,不必再感知 DaoSession 的存在。
Android 學習實作:打造簡易版微信(二)之登入與註冊
1 概述 從這篇開始,正式進入簡易版微信的開發。在深入之前,想先聊聊個人對 Android 程式開發的一些理解,未必正確,僅是自家心得。Android 開發不像大學時寫
開源項目 circular-progress-button 源碼解析:Drawable 驅動的按鈕變形動畫
這次要拆的是 circular-progress-button。選它的理由很直接:整個效果的骨架幾乎都由 Drawable 體系支撐起來,是研讀自定義 Drawable
Android 自訂加載狀態檢視:Loading、Empty、Error 一站式處理
為什麼需要統一加載狀態 應用程式在等待資料時,常需要顯示加載中、無網路、無資料或加載失敗等狀態。若每個頁面都各自實作,容易風格不一且難以維護。把這些狀態封裝成一個自訂 V
Android 啟動黑屏白屏怎麼辦?原因與 Theme 解法
為什麼啟動時會黑屏或白屏?許多 Android 新手在開發 App 時,會發現應用程式啟動瞬間出現黑屏或白屏。這其實不一定是錯誤,而是因為視窗已經建立,但尚未完成布局載入