編輯:Android 開發教學
專案原始碼下載
https://github.com/Wang-Jun-Chao/AndroidProjects
SQLite 是一個輕量級的關聯式資料庫,內建於 Android 系統中。建立資料庫時使用的核心 API 是 SQLiteOpenHelper,開發者需要自訂一個子類並覆寫相關回呼方法。
首先必須定義一個建構子:
// arg1:資料庫檔案名稱
// arg2:游標工廠
// arg3:資料庫版本
public MyOpenHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
兩個關鍵回呼:資料庫首次被建立時會呼叫 onCreate();資料庫版本升級時會呼叫 onUpgrade()。
MyOpenHelper oh = new MyOpenHelper(getContext(), "person.db", null, 1); SQLiteDatabase db = oh.getWritableDatabase();
兩個取得資料庫的方法有細微差別:
getWritableDatabase():開啟可讀寫的資料庫。
getReadableDatabase():磁碟空間不足時會開啟唯讀資料庫,否則開啟可讀寫資料庫。
建表動作通常寫在 onCreate() 中:
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table person (_id integer primary key autoincrement, "
+ "name varchar(20), phone varchar(20), money int)");
}
// 插入
db.execSQL("insert into person (name, phone, money) values (?, ?, ?)",
new Object[]{"tom", "110", 100});
// 刪除
db.execSQL("delete from person where name = ?", new Object[]{"_id = 1"});
// 修改
db.execSQL("update person set money = ? where name = ?",
new Object[]{200, "tom"});
// 查詢
Cursor cs = db.rawQuery("select name, phone from person where name = ?",
new String[]{"tom"});
若使用 JUnit 測試,可在測試方法執行前先透過 setUp() 完成初始化:
@Before
public void setUp() throws Exception {
oh = new MyOpenHelper(getContext(), "person.db", null, 1);
}
插入
ContentValues cv = new ContentValues();
cv.put("name", "tom");
cv.put("phone", "110");
cv.put("money", 100);
long i = db.insert("person", null, cv);
刪除
int i = db.delete("person", "name = ?", new String[]{"tom"});
修改
ContentValues cv = new ContentValues();
cv.put("money", 200);
int i = db.update("person", cv, "name = ?", new String[]{"tom"});
查詢
Cursor cs = db.query("person", new String[]{"name", "money"},
null, null, null, null, null);
while (cs.moveToNext()) {
String name = cs.getString(cs.getColumnIndex("name"));
String money = cs.getString(cs.getColumnIndex("money"));
System.out.println(name + " " + money);
}
兩種方式相比:SQL 語句更直接、彈性更高;API 方法則能避免拼接字串的風險,也不容易打錯欄位名。
交易用來保證多條 SQL 語句要嘛全部成功,要嘛全部失敗。最常見的場景就是銀行轉帳——扣款與入帳必須是不可分割的一體。
try {
db.beginTransaction();
// 執行多條更新語句
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
這裡有個容易忽略的細節:setTransactionSuccessful() 必須在 endTransaction() 之前呼叫,否則交易會被回滾。
先任意插入幾筆資料,接著定義業務用的 bean 類別 Person.java,然後把資料讀出來裝進集合:
Cursor cs = db.query("person", null, null, null, null, null, null);
List<Person> people = new ArrayList<Person>();
while (cs.moveToNext()) {
String name = cs.getString(cs.getColumnIndex("name"));
String phone = cs.getString(cs.getColumnIndex("phone"));
String money = cs.getString(cs.getColumnIndex("money"));
Person p = new Person(name, phone, money);
people.add(p);
}
再把集合中的資料逐筆加進版面容器:
LinearLayout ll = (LinearLayout) findViewById(R.id.ll);
for (Person p : people) {
TextView tv = new TextView(this);
tv.setText(p.toString());
ll.addView(tv);
}
資料量大時必須分頁,做法是在 query 的最後兩個參數填入 offset 與 limit:
Cursor cs = db.query("person", null, null, null, null, null, "_id asc", "0, 20");
Android 4.3 截屏嘗試與失敗原因分析
在 Android 4.3 上實作系統截屏並不容易。常見嘗試包含讀取 fb0、反射 SurfaceControl、自編譯隱藏 API、加入 core.jar/framew
淺析 Android 系統設計中的回調思想
越往裡走越會發現,Android(至少在應用層開發上)到處都是回調的影子:Activity 的生命週期、Fragment 的生命週期,全靠回調函數驅動;事件處理機制的一條
Android RoboGuice2 使用指南(2):第一個範例 Hello World
本例要實現的功能與 RoboGuice 1.x 版本的 Hello World 完全相同,差別只在改用 RoboGuice2.0 來實作。透過對照,你能清楚看到兩代之間的
用 Pull 方式建立與解析 XML(Android 系列之四)
Pull 是 Android 官方最推薦的 XML 處理方案,最大的優點是它內建在系統裡,不必額外引入任何第三方 jar。 Pull 的核心概念 Android 中與 X