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

Android 適配器教程(二):用 SimpleCursorAdapter 把資料庫攤成列表

編輯:關於 Android 程式設計

上一篇用 ArrayAdapter 建立了最基礎的列表,也說明了 Adapter 作為資料與視圖之間橋樑的本質。這篇接著在同一個 Demo 專案裡添第二個例子,主角是另一個原生 Adapter——SimpleCursorAdapter。

一、它解決了什麼問題

官方文件的描述是:一個把游標中的欄位對應到 XML 版面裡 TextView 或 ImageView 的簡易 Adapter;你可以指定要哪些欄位、要顯示到哪些控制項,以及描述這些控制項外觀的 XML 檔。

翻成白話:它讓「游標資料 → 列表顯示」這件事,不必再自己寫 getView。你只要告訴它「這個欄位配這個控制項」,映射就自動完成。實務上最典型的場景就是通訊錄、簡訊、通話紀錄——凡是 ContentProvider 查回來的游標,都能直接攤成列表。

二、動手做

(1)在 activity_main.xml 再加一顆按鈕,用來跳到這個範例。

(2)新增 SimpleCursorAdapterDemo 繼承 Activity,覆寫 onCreate。

(3)建立版面檔 simplecursoradapterdemo.xml,內容同樣是一個文字域加一個 ListView:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="這是 SimpleCursorAdapter 的一個例子" />

    <ListView
        android:id="@+id/simplecursoradapterlistview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</LinearLayout>

(4)回到 Activity,掛上 Adapter:

SimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to)

參數逐一拆解:context 傳 this;layout 是列表中「單列」的版面;c 是資料游標;而 from 與 to 一開始最容易讓人困惑——from 是你要取用的資料庫欄位名稱陣列,to 是單列版面中對應控制項的 id 陣列,兩者一對一、依索引配對。理解這層對應關係之後,用法其實非常省事。

三、資料從哪裡來:Cursor

先取得一個指向系統通訊錄的游標:

Cursor cursor = getContentResolver().query(People.CONTENT_URI, null, null, null, null);

再把它交給 Activity 代管:

startManagingCursor(cursor);

這一步的意義是讓游標的生命週期與 Activity 自動同步——Activity 銷毀時游標會被關閉,不必自己記著 recycle。省去手動管理,但也如前所述,代價是游標不能長命過 Activity。

SimpleCursorAdapter 建構子的前三個參數與 ArrayAdapter 概念上一致,差別在最後兩個:一個是欄位名稱的 String 陣列,一個是控制項 id 的 int 陣列,作用是把前者所表示的每一列資料,自動塞進後者對應的控制項裡。下面的寫法就是把 NAME 欄位映射到 id 為 text1 的控制項。

四、別忘了權限

讀取通訊錄屬於危險權限,必須在資訊清單中宣告,並在執行期向使用者申請:

<uses-permission android:name="android.permission.READ_CONTACTS" />

少了這一行(或未實際取得授權),query 會直接抛出 SecurityException,而錯誤訊息往往不夠明確,是初學者最常卡住的地方之一。

五、完整程式碼

public class SimpleCursorAdapterDemo extends Activity {

    private ListView lv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.simplecursoradapterdemo);

        lv = (ListView) findViewById(R.id.simplecursoradapterlistview);

        Cursor cursor = getContentResolver().query(People.CONTENT_URI, null, null, null, null);
        startManagingCursor(cursor);

        ListAdapter listAdapter = new SimpleCursorAdapter(this,
                android.R.layout.simple_expandable_list_item_1,
                cursor,
                new String[] { People.NAME },
                new int[] { android.R.id.text1 });

        lv.setAdapter(listAdapter);
    }
}

成果如下:

六、與上一篇的對照

把兩個範例擺在一起看,差異就清楚了:ArrayAdapter 吃的是「記憶體裡的集合」,資料型別與外觀都得自己張羅;SimpleCursorAdapter 吃的是「游標」,並額外提供 from/to 這組宣告式映射,讓欄位到控制項的對應不必寫成程式碼。

但方便有代價,有兩點要留意。第一,游標不會自己更新。資料變了之後必須呼叫 notifyDataSetChanged 或重新查詢,列表才會反映,這在實作即時性需求時容易踩坑。第二,版面檔裡的控制項 id 必須存在。to 陣列指向的 id 若在版面中找不到,執行期才會抛出錯誤,編譯階段完全不會提示。

下一篇會進入自訂 Adapter,看看當一列需要放圖片加多行文字、或需要 convertView 重用時,該怎麼自己接手 getView。

我也還是學生,水平有限,還望多指教。

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