Android中CursorAdapter的使用詳解

來源:互聯網
上載者:User

標籤:資料庫   newview   bindview   cursoradapter   chanagecursor   

      一、CursorAdapter介紹

CursorAdapter這個類是繼承於BaseAdapter的它是一個虛類它為Cursor和ListView串連提供了橋樑


二、CursorAdapter詳解
1.CursorAdapter的繼承關係圖

可以看出CursorAdapter是繼承於BaseAdapter的,它有一個直接的子類SimpleCursorAdapter
2.CursorAdapter的用法
我們首先看一下CursorAdapter的部分源碼:
 /**     * @see android.widget.ListAdapter#getCount()     */    public int getCount() {        if (mDataValid && mCursor != null) {            return mCursor.getCount();        } else {            return 0;        }    }       /**     * @see android.widget.ListAdapter#getItem(int)     */    public Object getItem( int position) {        if (mDataValid && mCursor != null) {            mCursor.moveToPosition(position);            return mCursor;        } else {            return null;        }    }    /**     * @see android.widget.ListAdapter#getItemId(int)     */    public long getItemId( int position) {        if (mDataValid && mCursor != null) {            if ( mCursor.moveToPosition(position)) {                return mCursor.getLong( mRowIDColumn);            } else {                return 0;            }        } else {            return 0;        }    }    /**     * @see android.widget.ListAdapter# getView(int, View, ViewGroup)     */    public View getView( int position, View convertView, ViewGroup parent) {        if (!mDataValid) {            throw new IllegalStateException( "this should only be called when the cursor is valid");        }        if (!mCursor.moveToPosition(position)) {            throw new IllegalStateException( "couldn't move cursor to position " + position);        }        View v;        if (convertView == null) {            v = newView( mContext, mCursor, parent);        } else {            v = convertView;        }        bindView(v, mContext, mCursor);        return v;    }

  從源碼中可以看出CursorAdapter是繼承了BaseAdapter後覆蓋它的getView方法在getView方法中調用了newView和bindView方法,我們在寫CursorAdapter時必須實現它的兩個方法
 /**     * Makes a new view to hold the data pointed to by cursor.     * @param context Interface to application's global information     * @param cursor The cursor from which to get the data. The cursor is already     * moved to the correct position.     * @param parent The parent to which the new view is attached to     * @return the newly created view.     */    public abstract View newView (Context context, Cursor cursor, ViewGroup parent);       /**     * Bind an existing view to the data pointed to by cursor     * @param view Existing view, returned earlier by newView     * @param context Interface to application's global information     * @param cursor The cursor from which to get the data. The cursor is already     * moved to the correct position.     */    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)源碼如下:   
/**     * Change the underlying cursor to a new cursor. If there is an existing cursor it will be     * closed.     *     * @param cursor The new cursor to be used     */    public void changeCursor (Cursor cursor) {        Cursor old = swapCursor(cursor);        if (old != null) {            old.close();        }    } swapCursor(cusor)的源碼如下:/**     * Swap in a new Cursor, returning the old Cursor.  Unlike     * {@link #changeCursor(Cursor)}, the returned old Cursor is <em>not</em>     * closed.     *     * @param newCursor The new cursor to be used.     * @return Returns the previously set Cursor, or null if there wasa not one.     * If the given new Cursor is the same instance is the previously set     * Cursor, null is also returned.     */    public Cursor swapCursor (Cursor newCursor) {        if (newCursor == mCursor) {            return null;        }        Cursor oldCursor = mCursor;        if (oldCursor != null) {            if ( mChangeObserver != null) oldCursor.unregisterContentObserver(mChangeObserver );            if ( mDataSetObserver != null) oldCursor.unregisterDataSetObserver(mDataSetObserver );        }        mCursor = newCursor;        if (newCursor != null) {            if ( mChangeObserver != null) newCursor.registerContentObserver(mChangeObserver );            if ( mDataSetObserver != null) newCursor.registerDataSetObserver(mDataSetObserver );            mRowIDColumn = newCursor.getColumnIndexOrThrow("_id" );            mDataValid = true;            // notify the observers about the new cursor            notifyDataSetChanged();        } else {            mRowIDColumn = -1;            mDataValid = false;            // notify the observers about the lack of a data set            notifyDataSetInvalidated();        }        return oldCursor;    }



從源碼中可以看出調用此方法後會把當前的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的主要代碼:
@Override     public View newView(Context context, Cursor cursor, ViewGroup parent) {                      ViewHolder viewHolder= new ViewHolder();           LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE );           View view=inflater.inflate(R.layout.item_contacts ,parent,false);                      viewHolder. tv_name=(TextView) view.findViewById(R.id.tv_showusername );           viewHolder. tv_phonenumber=(TextView) view.findViewById(R.id.tv_showusernumber );           view.setTag(viewHolder);           Log. i("cursor" ,"newView=" +view);            return view;     }          @Override     public void bindView(View view, Context context, Cursor cursor) {           Log. i("cursor" ,"bindView=" +view);           ViewHolder viewHolder=(ViewHolder) view.getTag();   //從資料庫中查詢姓名欄位           String name=cursor.getString(cursor.getColumnIndex(PersonInfo.NAME));   //從資料庫中查詢電話欄位           String phoneNumber=cursor.getString(cursor.getColumnIndex(PersonInfo.PHONENUMBER));                      viewHolder. tv_name.setText(name);           viewHolder. tv_phonenumber.setText(phoneNumber);     }
調用newView方法執行個體化條目,然後調用bindView繪製條目,當只繪製時不會調用newView方法。
(2)點擊儲存按鈕執行的方法
private void setClickListener() {                       btn_save.setOnClickListener( new OnClickListener() {                                 public void onClick(View v) {                                           userName=et_name.getText().toString();                    userPhoneNumber=et_phonenumber .getText().toString();                                       if( userName.equals( "")){                     Toast. makeText(MainActivity.this, "使用者名稱不可為空!",0).show();                      return;                    }                    if( userPhoneNumber.equals( "")){                     Toast. makeText(MainActivity.this,"電話不可為空", 0).show();                      return;                    }                                       ContentValues contentValues= new ContentValues();                    contentValues.put(PersonInfo. NAME, userName);                    contentValues.put(PersonInfo.PHONENUMBER ,userPhoneNumber );                    //把EditText中的文本插入資料庫                    dataBase.insert(PersonInfo. PERSON_INFO_TABLE, null,contentValues);                    //根據 _id 降序插敘資料庫保證最後插入的在最上面                    Cursor myCursor          = dataBase.query(PersonInfo. PERSON_INFO_TABLE, null, null, null, null, null, orderBy);                    //Cursor改變調用chanageCursor()方法                    myCursorAdapter.changeCursor(myCursor);                }           });     }

如果資料庫操作不熟可以看此部落格
     源碼戳HERE


Android中CursorAdapter的使用詳解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.