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

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

问题描述

Hello
我正在寻找使用光标适配器与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.

有两个主要部分使用 Cursor Adapter 与SQLite: / p>

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。在数据库中创建正确的游标。



在您的活动中:

1. Create a proper Cursor from the Database.

In your Activity:

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天全站免登陆