一、CursorAdapter介绍

CursorAdapter这个类是继承于BaseAdapter的它是一个虚类它为Cursor和ListView连接提供了桥梁

二、CursorAdapter详解

1.CursorAdapter的继承关系图

从图中可以看出CursorAdapter是继承于BaseAdapter的,它有一个直接的子类SimpleCursorAdapter

2.CursorAdapter的用法

我们首先看一下CursorAdapter的部分源码:

  1. /**
  2. * @see android.widget.ListAdapter#getCount()
  3. */
  4. public int getCount() {
  5. if (mDataValid && mCursor != null) {
  6. return mCursor.getCount();
  7. } else {
  8. return ;
  9. }
  10. }
  11.  
  12. /**
  13. * @see android.widget.ListAdapter#getItem(int)
  14. */
  15. public Object getItem( int position) {
  16. if (mDataValid && mCursor != null) {
  17. mCursor.moveToPosition(position);
  18. return mCursor;
  19. } else {
  20. return null;
  21. }
  22. }
  23.  
  24. /**
  25. * @see android.widget.ListAdapter#getItemId(int)
  26. */
  27. public long getItemId( int position) {
  28. if (mDataValid && mCursor != null) {
  29. if ( mCursor.moveToPosition(position)) {
  30. return mCursor.getLong( mRowIDColumn);
  31. } else {
  32. return ;
  33. }
  34. } else {
  35. return ;
  36. }
  37. }
  38.  
  39. /**
  40. * @see android.widget.ListAdapter# getView(int, View, ViewGroup)
  41. */
  42. public View getView( int position, View convertView, ViewGroup parent) {
  43. if (!mDataValid) {
  44. throw new IllegalStateException( "this should only be called when the cursor is valid");
  45. }
  46. if (!mCursor.moveToPosition(position)) {
  47. throw new IllegalStateException( "couldn't move cursor to position " + position);
  48. }
  49. View v;
  50. if (convertView == null) {
  51. v = newView( mContext, mCursor, parent);
  52. } else {
  53. v = convertView;
  54. }
  55. bindView(v, mContext, mCursor);
  56. return v;
  57. }
  58.  
  59. 从源码中可以看出CursorAdapter是继承了BaseAdapter后覆盖它的getView方法在getView方法中调用了newViewbindView方法,我们在写CursorAdapter时必须实现它的两个方法
  60. /**
  61. * Makes a new view to hold the data pointed to by cursor.
  62. * @param context Interface to application's global information
  63. * @param cursor The cursor from which to get the data. The cursor is already
  64. * moved to the correct position.
  65. * @param parent The parent to which the new view is attached to
  66. * @return the newly created view.
  67. */
  68. public abstract View newView (Context context, Cursor cursor, ViewGroup parent);
  69.  
  70. /**
  71. * Bind an existing view to the data pointed to by cursor
  72. * @param view Existing view, returned earlier by newView
  73. * @param context Interface to application's global information
  74. * @param cursor The cursor from which to get the data. The cursor is already
  75. * moved to the correct position.
  76. */
  77. public abstract void bindView(View view, Context context, Cursor cursor);
从源码的 getView( int position, View convertView, ViewGroup parent)方法中我们可以看出:
(1)newView:并不是每次都被调用的,它只在实例化的时候调用,数据增加的时候也会调用,但是在重绘(比如修改条目里的TextView的内容)的时候不会被调用
(2)bindView:从代码中可以看出在绘制Item之前一定会调用bindView方法它在重绘的时候也同样被调用
3.CursorAdapter还有一个重要的方法 public void changeCursor (Cursor cursor)
源码如下:
  1. /**
  2. * Change the underlying cursor to a new cursor. If there is an existing cursor it will be
  3. * closed.
  4. *
  5. * @param cursor The new cursor to be used
  6. */
  7. public void changeCursor (Cursor cursor) {
  8. Cursor old = swapCursor(cursor);
  9. if (old != null) {
  10. old.close();
  11. }
  12. }
  13. swapCursor(cusor)的源码如下:
  14.  
  15. /**
  16. * Swap in a new Cursor, returning the old Cursor. Unlike
  17. * {@link #changeCursor(Cursor)}, the returned old Cursor is <em>not</em>
  18. * closed.
  19. *
  20. * @param newCursor The new cursor to be used.
  21. * @return Returns the previously set Cursor, or null if there wasa not one.
  22. * If the given new Cursor is the same instance is the previously set
  23. * Cursor, null is also returned.
  24. */
  25. public Cursor swapCursor (Cursor newCursor) {
  26. if (newCursor == mCursor) {
  27. return null;
  28. }
  29. Cursor oldCursor = mCursor;
  30. if (oldCursor != null) {
  31. if ( mChangeObserver != null) oldCursor.unregisterContentObserver(mChangeObserver );
  32. if ( mDataSetObserver != null) oldCursor.unregisterDataSetObserver(mDataSetObserver );
  33. }
  34. mCursor = newCursor;
  35. if (newCursor != null) {
  36. if ( mChangeObserver != null) newCursor.registerContentObserver(mChangeObserver );
  37. if ( mDataSetObserver != null) newCursor.registerDataSetObserver(mDataSetObserver );
  38. mRowIDColumn = newCursor.getColumnIndexOrThrow("_id" );
  39. mDataValid = true;
  40. // notify the observers about the new cursor
  41. notifyDataSetChanged();
  42. } else {
  43. mRowIDColumn = -;
  44. mDataValid = false;
  45. // notify the observers about the lack of a data set
  46. notifyDataSetInvalidated();
  47. }
  48. return oldCursor;
  49. }
从源码中可以看出调用此方法后会把当前的mCursor置为新传过来的cursor把原来的cursor返回去并关掉
作用:当我们的Cursor变化时调用此方法
adapter.changeCursor(cursor),它的功能类似于adapter.notifyDataSetChanged()方法
4.之前的疑惑
 之前我一直对cursor是怎么移动的疑惑,比方说cursor中有40条数据,那么它是怎样一行一行移动cursor把这40条数据显示出来的,看过源码后发现其实很简单,
它在getCount()方法中return mCursor.getCount();然后在getView方法的时候调用了mCursor.moveToPosition(position)其实和BaseAdapter的原理是一样的,这样就可以一条一条的绘制条目了。
三、源码小案例:
1.案例功能

在EditText中输入姓名和电话,点击保存后会显示在下面的listView中

2.代码片段
(1)MyCursorAdapter的主要代码:
  1. @Override
  2. public View newView(Context context, Cursor cursor, ViewGroup parent) {
  3.  
  4. ViewHolder viewHolder= new ViewHolder();
  5. LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE );
  6. View view=inflater.inflate(R.layout.item_contacts ,parent,false);
  7.  
  8. viewHolder. tv_name=(TextView) view.findViewById(R.id.tv_showusername );
  9. viewHolder. tv_phonenumber=(TextView) view.findViewById(R.id.tv_showusernumber );
  10. view.setTag(viewHolder);
  11. Log. i("cursor" ,"newView=" +view);
  12. return view;
  13. }
  14.  
  15. @Override
  16. public void bindView(View view, Context context, Cursor cursor) {
  17. Log. i("cursor" ,"bindView=" +view);
  18. ViewHolder viewHolder=(ViewHolder) view.getTag();
  19. //从数据库中查询姓名字段
  20. String name=cursor.getString(cursor.getColumnIndex(PersonInfo.NAME));
  21. //从数据库中查询电话字段
  22. String phoneNumber=cursor.getString(cursor.getColumnIndex(PersonInfo.PHONENUMBER));
  23.  
  24. viewHolder. tv_name.setText(name);
  25. viewHolder. tv_phonenumber.setText(phoneNumber);
  26. }
调用newView方法实例化条目,然后调用bindView绘制条目,当只绘制时不会调用newView方法。

(2)点击保存按钮执行的方法

  1. private void setClickListener() {
  2.  
  3. btn_save.setOnClickListener( new OnClickListener() {
  4.  
  5. public void onClick(View v) {
  6.  
  7. userName=et_name.getText().toString();
  8. userPhoneNumber=et_phonenumber .getText().toString();
  9.  
  10. if( userName.equals( "")){
  11. Toast. makeText(MainActivity.this, "用户名不能为空!",).show();
  12. return;
  13. }
  14. if( userPhoneNumber.equals( "")){
  15. Toast. makeText(MainActivity.this,"电话不能为空", ).show();
  16. return;
  17. }
  18.  
  19. ContentValues contentValues= new ContentValues();
  20. contentValues.put(PersonInfo. NAME, userName);
  21. contentValues.put(PersonInfo.PHONENUMBER ,userPhoneNumber );
  22. //把EditText中的文本插入数据库
  23. dataBase.insert(PersonInfo. PERSON_INFO_TABLE, null,contentValues);
  24. //根据 _id 降序插叙数据库保证最后插入的在最上面
  25. Cursor myCursor = dataBase.query(PersonInfo. PERSON_INFO_TABLE, null, null, null, null, null, orderBy);
  26. //Cursor改变调用chanageCursor()方法
  27. myCursorAdapter.changeCursor(myCursor);
  28. }
  29. });
  30. }

Android CursorAdapter的使用详解的更多相关文章

  1. 《Android NFC 开发实战详解 》简介+源码+样章+勘误ING

    <Android NFC 开发实战详解>简介+源码+样章+勘误ING SkySeraph Mar. 14th  2014 Email:skyseraph00@163.com 更多精彩请直接 ...

  2. Android开发之InstanceState详解

    Android开发之InstanceState详解   本文介绍Android中关于Activity的两个神秘方法:onSaveInstanceState() 和 onRestoreInstanceS ...

  3. ANDROID L——Material Design详解(UI控件)

    转载请注明本文出自大苞米的博客(http://blog.csdn.net/a396901990),谢谢支持! Android L: Google已经确认Android L就是Android Lolli ...

  4. android bundle存放数据详解

    转载自:android bundle存放数据详解 正如大家所知道,Activity之间传递数据,是将数据存放在Intent或者Bundle中 例如: 将数据存放倒Intent中传递: 将数据放到Bun ...

  5. Cordova 打包 Android release app 过程详解

    Cordova 打包 Android release app 过程详解 时间 -- :: SegmentFault 原文 https://segmentfault.com/a/119000000517 ...

  6. Android中Service(服务)详解

    http://blog.csdn.net/ryantang03/article/details/7770939 Android中Service(服务)详解 标签: serviceandroidappl ...

  7. 给 Android 开发者的 RxJava 详解

    我从去年开始使用 RxJava ,到现在一年多了.今年加入了 Flipboard 后,看到 Flipboard 的 Android 项目也在使用 RxJava ,并且使用的场景越来越多 .而最近这几个 ...

  8. Android中mesure过程详解

    我们在编写layout的xml文件时会碰到layout_width和layout_height两个属性,对于这两个属性我们有三种选择:赋值成具体的数值,match_parent或者wrap_conte ...

  9. Android中Intent组件详解

    Intent是不同组件之间相互通讯的纽带,封装了不同组件之间通讯的条件.Intent本身是定义为一个类别(Class),一个Intent对象表达一个目的(Goal)或期望(Expectation),叙 ...

随机推荐

  1. 内存卡(TF或其它)的标准

    内存卡(TF或其它)的标准 来源 https://zh.wikipedia.org/wiki/SDXC 一般的内存卡是SD2.0的规范的,就是 Class10(10M/sec)或低于 Class10 ...

  2. cf1051F. The Shortest Statement(最短路/dfs树)

    You are given a weighed undirected connected graph, consisting of nn vertices and mm edges. You shou ...

  3. MFC ClistCtr锁定隐藏某一列

    通过设置列的宽度为0, 可以隐藏列表框的某一列,但是用户通过拖动列表框的大小,隐藏的列,可能又被显示出来了. 我们可以自己写一个CListEx继承CListCtr,然后捕获拖动的消息,对该消息进行特殊 ...

  4. 【Codeforces Round #452 (Div. 2) B】Months and Years

    [链接] 我是链接,点我呀:) [题意] 在这里输入题意 [题解] 闰,平,平 平,闰,平 平,平,闰 平,平,平 4种情况都考虑到就好. 可能有重复的情况. 但是没关系啦. [代码] #includ ...

  5. 关于java中String的一点理解

      String类是java的最基本类之中的一个,非常好的掌握它的原理非常是必要的!   1.String的Final类型的.是不可继承 的.final类默认的方法都为final类型,保证了方法不能被 ...

  6. [Javascript AST] 1. Continue: Write a simple Babel plugin

    We want to write a Babel Plugin, which move 'const versionRegex = /(/d+)\.(/d+)\.(/d+)/gi' out of fu ...

  7. Fragment 实现的 分类 效果

    Fragment   实现的 分类 效果 布局文件的信息: <LinearLayout xmlns:android="http://schemas.android.com/apk/re ...

  8. 安卓手机运行WINDOWS

    http://www.pcdiy.com.tw/detail/1974 我的ZenFone 2手机可以跑Windows啦! 就在台风来袭,有人正准备去泛舟的那天,国外的XDA论坛神人则是选择让自己的Z ...

  9. 19. Spring Boot Shiro 权限管理

    转自:https://blog.csdn.net/catoop/article/details/50520958

  10. SQLite基础学习

    SQLite是一款轻量级数据库,集成于android中,以下从分享一下自己学习的. 在查阅资料时有一些好的说明就直接用了: 主要的curd语句 以下SQL语句获取5条记录,跳过前面3条记录 selec ...