Cursor使用以及各种ListAdapter适配器(自定义)的使用
1.public interface Cursor
|-android.database.Cursor
Cursor一般是用来存储查询结果的集合,特别是database的query方法的返回值是Cursor对象,而Cursor对象则保存了查询的结果。与Iterator迭代器相似。
常用方法:
moveToFirst();//该方法使Cursor的游标指向数据记录的第一行,用于从第一行开始遍历
moveToNext();//判断下一行是否有记录,有则指向下一行。
Xxxx getXxxx(int columnIndex);//根据columnIndex,获取Xxx数据类型的值,
int getColumnIndexOrThrow(String columnName)//根据列名获取它的index值
注意:可以使用Activity的startManagingCursor(cursor);方法对创建的cursor的生命周期进行管理,便于回收销毁该cursor。
案例:
Xxxx getXxxx (getColumnIndexOrThrow(String columnName));//根据列名,获取该表上该列名上的值(Xxxx);
遍历:
cursor.moveToFirst()
while(cursor.moveToNext())
{
cursor.xxx();//遍历结果集合
}
2.public abstract class CursorAdapter
extends BaseAdapter
implements Filterable
子类为下面两个子类
实现CursorAdapter时需要,实现以下的抽象方法:
//创建一个新的View对象 @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = super.newView(context, cursor, parent); Tag tag = new Tag(); tag.icon = (ImageView) view.findViewById(R.id.book_icon); tag.author = (TextView) view.findViewById(R.id.author); tag.name = (TextView) view.findViewById(R.id.book_name); tag.year = (TextView) view.findViewById(R.id.year); view.setTag(tag); return view; } //将cursor指向的数据和创建的View对象进行绑定 @Override public void bindView(View view, Context context, Cursor cursor) { Tag tag = (Tag) view.getTag(); tag.author.setText(cursor.getString(cursor .getColumnIndexOrThrow(Publisher.AUTHOR.NAME))); tag.name.setText(cursor.getString(cursor .getColumnIndexOrThrow(Publisher.BOOK.NAME))); tag.year.setText(cursor.getString(cursor .getColumnIndexOrThrow(Publisher.BOOK.PUBLISH_YEAR))); Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.icon); tag.icon.setImageBitmap(icon); } //view里面的各个UI组件集合 class Tag { public ImageView icon; public TextView name; public TextView author; public TextView year; }
3.public abstract class ResourceCursorAdapter
作用:通过该adapter将Cursor的数据显示在View上
ResourceCursorAdapter(Context context, int layout, Cursor c)
4.public class SimpleCursorAdapter
SimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to)