Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 心得 4.5——SQLite 資料庫事務處理與 ListView 列表顯示

編輯:關於 Android 程式設計

本文整理兩個實用主題:SQLite 的事務(Transaction)處理,以及如何用 ListView 把資料庫內容以列表形式顯示出來。

一、SQLite 事務處理

使用 SQLiteDatabase 的 beginTransaction() 可以開啟一個事務。當程式執行到 endTransaction() 時,會檢查事務的成功標誌:若在 endTransaction() 之前呼叫了 setTransactionSuccessful(),則提交事務;若沒有呼叫,則回滾事務。範例如下:

[java]
SQLiteDatabase db = ....;

db.beginTransaction();// 開始事務
try {
    db.execSQL("insert into person(name, age) values(?,?)", new Object[]{"傳智播客", 4});
    db.execSQL("update person set name=? where personid=?", new Object[]{"傳智", 1});
    db.setTransactionSuccessful();// 設定成功標誌,執行到 endTransaction() 時會提交
} finally {
    db.endTransaction();// 依標誌決定提交或回滾
}
db.close();

如此一來,這兩條 SQL 語句就會在同一個事務中執行,具備原子性——要嘛全部成功,要嘛全部回滾。

二、ListView 列表顯示

先在 layout 資料夾下建立一個 item.xml(水平線性配置的條目畫面),再在 main.xml 中放入 <ListView/>。把資料綁定到 ListView 有三種常見方式:

show():使用 SimpleAdapter,把 List<HashMap> 資料綁到條目上;
show2():使用 SimpleCursorAdapter,直接把資料庫的 Cursor 綁到條目上;
show3():使用自訂的 BaseAdapter(PersonAdapter),在特殊需求下最靈活。

以 SimpleCursorAdapter 為例:

[java]
Cursor cursor = personService.getCursorScrollData(0, 20);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.item, cursor,
    new String[]{"name", "phone", "amount"}, new int[]{R.id.name, R.id.phone, R.id.amount});
listView.setAdapter(adapter);

若使用自訂的 PersonAdapter,核心在於重寫 getView 方法,並善用 convertView 與 ViewCache(透過 setTag 快取 view)來避免重複 inflate,提升列表滾動效能:

[java]
public View getView(int position, View convertView, ViewGroup parent) {
    TextView nameView, phoneView, amountView;
    if(convertView == null){
        convertView = inflater.inflate(resource, null);
        nameView = (TextView) convertView.findViewById(R.id.name);
        phoneView = (TextView) convertView.findViewById(R.id.phone);
        amountView = (TextView) convertView.findViewById(R.id.amount);
        ViewCache cache = new ViewCache();
        cache.nameView = nameView;
        cache.phoneView = phoneView;
        cache.amountView = amountView;
        convertView.setTag(cache);
    }else{
        ViewCache cache = (ViewCache) convertView.getTag();
        nameView = cache.nameView;
        phoneView = cache.phoneView;
        amountView = cache.amountView;
    }
    Person person = persons.get(position);
    nameView.setText(person.getName());
    phoneView.setText(person.getPhone());
    amountView.setText(person.getAmount().toString());
    return convertView;
}

此外,透過 listView.setOnItemClickListener,在回呼中即可取得被點擊項目的資料(無論是 Cursor 還是自訂物件),進而做出對應處理。掌握事務與列表顯示這兩大主題,就能應付大量資料驅動型的 Android 應用場景。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved