光标适配器和 sqlite 示例 [英] Cursor adapter and sqlite example

查看:44
本文介绍了光标适配器和 sqlite 示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Hello I am looking for sample code in which cursor adapter is used with sqlite?

推荐答案

非常简单的例子.

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

Really simple example.

Here is a really simple, but very effective, example. Once you have the basics down you can easily build off of it.

在 SQLite 中使用游标适配器有两个主要部分:

There are two main parts to using a Cursor Adapter with SQLite:

  1. 从数据库创建一个合适的游标.

创建自定义光标适配器,从数据库中获取光标数据并将其与您打算表示的视图配对数据与.

Create a custom Cursor Adapter that takes the Cursor data from the database and pairs it with the View you intend to represent the data with.

1.从数据库创建一个合适的 Cursor.

在您的活动中:

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 创建视图.

2. Create a Custom Cursor Adapter.

Note: Extending from ResourceCursorAdapter 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")));
    }
}

这篇关于光标适配器和 sqlite 示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆