このエントリーをはてなブックマークに追加

2010年2月14日日曜日

CursorAdapter requires a column named "_id"

[In English]
When I used SimpleCursorAdapter to display some data on ListView, I had an Exception.


private SQLiteDatabase mDb;
private SimpleCursorAdapter mAdapter;
private ListView mListView;

....
....
Cursor c = mDb.rawQuery(SELECT_SOME_MEMBERS_SQL, null);
startManagingCursor(c);
String[] from = new String[] {MEMBER_NAME, MEMBER_AGE, NOTE};
int[] to = new int[]{R.id.TextView_name, R.id.TextView_age, R.id.TextView_note};
mAdapter = new SimpleCursorAdapter(this, R.layout.members_layout, c, from, to);
mListView.setAdapter(mAdapter);
....
....

The above sample code seems fine. But if "SELECT_SOME_MEMBERS_SQL" does not have "_id" column,
this sample cause IllegalArgumentException.
So if you use Database(SQLite) in Android Applications, it is better to add a column named "_id" to all tables to use CursorAdapter.
Or you need to write sql state "select member_id as _id from member_talbe where ....." to get Cursor.

You also can find this matter at Android Developer Site
"Adapter that exposes data from a Cursor to a ListView widget. The Cursor must include a column named "_id" or this class will not work."



[In Japanese]
SimplerCursorAdapterを使って、ListView上にデータを表示させる際に、例外に遭遇しました。


private SQLiteDatabase mDb;
private SimpleCursorAdapter mAdapter;
private ListView mListView;
....
....
....
Cursor c = mDb.rawQuery(SELECT_SOME_MEMBERS_SQL, null);
startManagingCursor(c);
String[] from = new String[] {MEMBER_NAME, MEMBER_AGE, NOTE};
int[] to = new int[]{R.id.TextView_name, R.id.TextView_age, R.id.TextView_note};
mAdapter = new SimpleCursorAdapter(this, R.layout.members_layout, c, from, to);
mListView.setAdapter(mAdapter);
....
....

上記のサンプルコードは一見正常に動くように見ますが、"SELECT_SOME_MEMBERS_SQL"に"_id"カラムがないとIllegalArgumentExceptionが発生します。
そのため、データベース(SQLite)を使用したAndroidアプリケーションをつくる場合には、全てのテーブルに"_id"カラムを加えておくとよいと思います。
もしくは、"select member_id as _id from member_talbe where ....."のようなSQL文でCursorを取得する必要があります。

Android Developerサイトに本件に関する注意の記載があります。
"Adapter that exposes data from a Cursor to a ListView widget. The Cursor must include a column named "_id" or this class will not work."

0 件のコメント:

コメントを投稿