
第十三課:Sqlite Database
本文介紹如何在android apps中使用sqlite database。Sqlite是近年十分流行的小型本地資料庫。由於支持 資料庫的ACID屬性,且小巧快速,系統資源要求少,很適合用於手機等平台。 學會在android中使用sqlite是很重要的,官方也有個很好的notepad tutorial,可是對初學來說不太易。 這裡會把notepad tutorial作適度簡化,另初學者更易吸收。
這demo名為boookmark demo,它接受用戶輸入自己的boookmark title,和url,用戶可以新增、移除、編輯及清除全部資料。 這個範例設計包括1個ListActivity、一個Input activity、和一個database helper class。Database helper是這次的的主要重點。
該Database helper中是一個幫助存取Sqlite的helper class,SQLiteDatabase就是android中的sqlite database。當初次使用sqlite時,你要建立一個新的database和加入新的table。
private SQLiteDatabase mDB;
private DBHelper mDBHelper;
private static class DBHelper extends SQLiteOpenHelper{
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DB_CREATE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL(DB_UPGRADE);
onCreate(db);
}
}
在這helper class中,你可使用SQLiteDatabase和SQLiteOpenHelper去提供以下功能:
取得一個可讀寫的database:
mDBHelper = new DBHelper(mCtx); mDB = mDBHelper.getWritableDatabase(); //important
關閉database:
mDBHelper.close();
加入新record:
ContentValues v = new ContentValues(); v.put(COL_TITLE, title); v.put(COL_URL, url); return mDB.insert(DB_TABLE, null, v);
刪除record:
mDB.delete(DB_TABLE, COL_ID + "="+ id, null);
讀取record:
mDB.query(DB_TABLE, new String[] {COL_ID, COL_TITLE, COL_URL},
null, null, null, null, null);
更新record:
ContentValues v = new ContentValues(); v.put(COL_TITLE, title); v.put(COL_URL, url); mDB.update(DB_TABLE, v, COL_ID + "=" + id, null);
把直接存取sqlite的代碼都放在這helper class中,可以把database logic跟ListActivity上的application/business logic都分離開,易於管理。 在ListActivity用來顯示database中的record。同時,它也提供context menu和option menu,讓用戶可以按自己的需要,呼叫不同database helper的method,從而透過這些method去執行open(),close(),delete(),update(),query()等sqliteDatabase的方法。
Download: Source code
PART 1:
PART 2
PART 3
PART 4