这里有一个非常简单但非常有效的例子.一旦你有了基本的东西,你就可以很容易地在它的基础上建立起来.
将Cursor Adapter与SQLite一起使用有两个主要部分:
从数据库中创建适当的Cursor.
创建一个定制的Cursor Adapter,它从数据库中获取Cursor个数据,并将其与要表示数据的View配对.
在您的活动中:
SQLiteOpenHelper sqLiteOpenHelper = new SQLiteOpenHelper(
context, DATABASE_NAME, null, DATABASE_VERSION);
SQLiteDatabase sqLiteDatabase = sqLiteOpenHelper.getReadableDatabase();
String query = "SELECT * FROM clients ORDER BY company_name ASC"; // No trailing ';'
Cursor cursor = sqLiteDatabase.rawQuery(query, null);
ClientCursorAdapter adapter = new ClientCursorAdapter(
this, R.layout.clients_listview_row, cursor, 0 );
this.setListAdapter(adapter);
Note: Extending from 100 assumes you use XML to create your views.
public class ClientCursorAdapter extends ResourceCursorAdapter {
public ClientCursorAdapter(Context context, int layout, Cursor cursor, int flags) {
super(context, layout, cursor, flags);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView name = (TextView) view.findViewById(R.id.name);
name.setText(cursor.getString(cursor.getColumnIndex("name")));
TextView phone = (TextView) view.findViewById(R.id.phone);
phone.setText(cursor.getString(cursor.getColumnIndex("phone")));
}
}