`
huakewoniu
  • 浏览: 46518 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论

Cursor与Adapter

阅读更多

来自: http://hi.baidu.com/lfcaolibin/blog/item/2ce306ec77cebd4478f055b4.html

Cursor与Adapter结合使用

查询数据库均会把查询的结果包装在一个Cursor的子类对象中返回。Cursor就像是位于结果集之上的一个游标,可以对结果集进行向前、向后或 随机的访问。而Cursor本身是一个接口类,提供了对结果集访问的一些抽象方法,根据功能的不同在其子类有着不同的实现。要控制查询时返回的 Cursor类型,可以自定义一个继承自CursorFactory类通过实现其newCursor()方法来返回需要的Cursor子类对象,但在 CursorFactory传入null的默认情况下,查询操作会返回一个指向第一行数据之前的SQLiteCursor的对象。

对Cursor中常用的一些方法的介绍。

 

有关Cursor的常用方法

Cursor-Class

在实际的应用编写过程中,更多是通过适配器(Adapter)来将Cursor与适配器控件联系起来。Android为Cursor提供了一个抽象 类CursorAdapter,可以方便实现Cursor与适配器的连接。只需要创建一个继承自CursorAdapter的类,实现其 bindView()和newView()两个抽象方法,或根据需要重新实现其他方法就可以用此类来构造一个可适配Cursor的适配器。下面是关于 bindView()和newView()两个抽象方法需要实现的内容。

  • public void bindView(View view, Context context, Cursor cursor)
    重用一个已有的view,使其显示当前cursor所指向的数据。
  • public View newView(Context context, Cursor cursor, ViewGroup parent)
    为cursor所指向的数据新建一个View对象,并显示其数据。

另外还需要注意的是,传入到CursorAdapter中的Cursor结果集必须包含有列名为_id的列,否则CursorAdapter将不会起作用。

Adapter 的作用是什么,想必大家看了Android SDK中的原文就一目了然:
An Adapter object acts as a bridge between an AdapterView and the underlying data for that view. The Adapter provides access to the data items. The Adapter is also responsible for making a View for each item in the data set.

Adapter-View

已经介绍到了几种Android已经实现好了的适配器,其中SimpleCursorAdapter就是为Cursor对象专门实现的一种方便使用的适配器类,下面是对其构造方法传入参数的介绍:

public SimpleCursorAdapter (Context contex, int layout, Cursor c, String[]from, int[] to)

  • context,当前程序的上下文对象。
  • layout,用来描述如何显示在适配器控件上的布局文件的R类引用。
  • from,由需要显示出来的列名组成的字符串数组。
  • to,由layout所指定的布局文件中子控件的id所组成的整形数组,与from相对应。

综合前面的说明,举个具体例子如下:

变量以便在程序中引用:
TextView display;
Spinner s;

填充Spinner控件的代码:
s = (Spinner)findViewById(R.id.spinner);
display = (TextView)findViewById(R.id.display);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item,
c,
new String[] { MyHelper.COUNTRY},
new int[] {android.R.id.text1});
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
s.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> adapter,View v,int pos, long id)
{
c.moveToPosition(pos);
display.setText(c.getString(codeIndex));
}
public void onNothingSelected(AdapterView<?> arg0) {}
});

首先通过id分别获得TextView和Spinner对象的引用,然后使用之前查询返回的Cursor和Android 自带的Spinner子控件的布局构造一个SimpleCursorAdapter,再调用setDrop-DownViewResource()方法来 设置点开Spinner后显示子控件的布局,最后设置Spinner的适配器为adapter并对其子控件被选取的事件设置一个监听器。需要注意的是 Spinner不支持设置点击事件的监听器(OnClickListener),强行设置的话会抛出异常。最后程序运行的结果,如下图所示:

Spinner

为了您的安全,请只打开来源可靠的网址

打开网站    取消

来自: http://hi.baidu.com/lfcaolibin/blog/item/2ce306ec77cebd4478f055b4.html
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics