当前位置:首页 > 数据库 > SQlite

android – 游标适配器和sqlite示例

你好
我正在寻找与sqlite一起使用游标适配器的示例代码?

解决方法:

真的很简单的例子.

这是一个非常简单但非常有效的例子.一旦你掌握了基础知识,你就可以轻松地建立它.

使用带有SQLite的Cursor Adapter有两个主要部分:

>从数据库中创建正确的光标.
>创建一个自定义Cursor Adapter,它从数据库中获取Cursor数据,并将其与您打算用来表示数据的View配对.

1.从数据库中创建适当的光标.

在您的活动中:

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);

2.创建自定义光标适配器.

注意:从ResourceCursorAdapter扩展假定您使用XML来创建视图.

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")));
    }
}

【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!