CursorAdapter和SimpleCursorAdapte

示例一

简单的例子说明一下,使用CursorAdapter读取数据库里,需要的数据,把它显示到listview上。

ListView数据来自数据库

CursorAdapter 继承了 BaseAdapter

好处:仅加载需要显示的数据,性能好

 

使用方法:

1.实现两个参数构造方法

2.重写newView()方法

 layout->view

3.重写bindView()方法

 view.set

 

数据更新:

adapter.changeCursor(cursor);

adapter.notifyDataSetChanged()

 

代码如下:


01. public class MySqliteOpenhelper extends SQLiteOpenHelper
02. {
03.  
04. public MySqliteOpenhelper(Context context,  int version)
05. {
06. super(context, "dianhuaben.db"null, version);
07. }
08. @Override
09. public void onCreate(SQLiteDatabase db)
10. {//注意:使用CursorAdapter时,创建表必须有以_id为列名的列
11. String sql = "CREATE TABLE dhb (_id INTEGER PRIMARY KEY AUTOINCREMENT,name VARCHAR(20),phone VARCHAR(20))";
12. db.execSQL(sql);
13. }
14. @Override
15. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
16. {
17. }
18. }

使用CursorAdapter的代码如下:

 

01. public void createCursorAdapter(Cursor cursor)
02. //游标适配器,构造方法,传入cursor
03. mAdapter = new CursorAdapter(this, cursor)
04. {//重写两个方法
05. @Override
06. public View newView(Context context, Cursor cursor, ViewGroup parent)
07. {//找到布局和控件
08. ViewHolder holder = new ViewHolder();
09. LayoutInflater inflater = getLayoutInflater();
10. View inflate = inflater.inflate(R.layout.listview_item, null);
11. holder.item_tv_name = (TextView) inflate.findViewById(R.id.item_tv_name);
12. holder.item_tv_phone = (TextView) inflate.findViewById(R.id.item_tv_phone);
13. inflate.setTag(holder);
14. return inflate;//返回的view传给bindView。
15. }
16.  
17. @Override
18. public void bindView(View view, Context context, Cursor cursor)
19. {//复用布局。www.it165.net
20. //                把数据设置到界面上
21. ViewHolder holder = (ViewHolder) view.getTag();
22. String name = cursor.getString(cursor.getColumnIndex("name"));
23. String phone = cursor.getString(cursor.getColumnIndex("phone"));
24. holder.item_tv_name.setText(name);
25. holder.item_tv_phone.setText(phone);
26. }
27.  
28. };
29.  
30. };

另一种是使用SimpleCursorAdapter,简化了代码,同样达到如上的效果

SimpleCursorAdapter继承了CursorAdapter,用法类似SimpleAdapter。

代码如下:



1. public void createSimpleCursorAdapter(Cursor cursor)
2. {// SimpleCursorAdapter继承了CursorAdapter继承了BaseAdapter
3. String[] from = {TABLE_NAME_NAME,TABLE_NAME_PHONE};//列名与控件id一一对应
4. int[] to = {R.id.item_tv_name,R.id.item_tv_phone};
5. //用的是SimpleCursorAdapter,用法和simpleAdapter相似
6. mAdapter = new SimpleCursorAdapter(MainActivity.this, R.layout.listview_item, cursor, from, to);
7. }

注意:使用SimpleCursorAdapter,时,创建表必须有以_id为列名的列


示例二


CursorAdapter
继承于BaseAdapter是个虚类,它为cursor和ListView提供了连接的桥梁。           
public abstract class
    CursorAdapter
        extends BaseAdapter
直接子类只有ResourceCursorAdapter
Class Overview
Adapter that exposes data from a Cursor to a ListView widget. 
The Cursor must include a column named "_id" or this class will not work.

注意cursor的必须要有个命名为"
_id "的列。比如Contacts._ID就为" _id "
必须实现以下函数

abstract View          newView (Context  context, Cursor  cursor, ViewGroup  parent)
    Makes a new view to hold the data pointed to by cursor.
abstract void          bindView (View  view, Context  context, Cursor  cursor)
    Bind an existing view to the data pointed to by cursor
注意
newView该函数第一次回调用后,如果数据增加后也会再调用,但是重绘是不会调用的。
数据增加后,回调用该函数来生成与新增数据相对应的view。
bindView函数第一次回调用后,如果数据更新也会再调用,但重绘会再次调用的。
【总的来说应该是在调用bindView如果发现view为空会先调用newView来生成view】
i
[java] view plaincopy
  1. <span style="font-size:16px;">mport java.util.List;  
  2. import android.app.Activity;  
  3. import android.app.ListActivity;  
  4. import android.os.Bundle;  
  5. import android.os.Handler;  
  6. import android.content.Context;  
  7. import android.content.ContentValues;  
  8. import android.database.Cursor;  
  9. import android.view.LayoutInflater;  
  10. import android.view.View;  
  11. import android.widget.ListView;  
  12. import android.view.ViewGroup;  
  13. import android.widget.ArrayAdapter;  
  14. import android.widget.CursorAdapter;  
  15. import android.widget.TextView;  
  16. import android.provider.ContactsContract.Contacts;  
  17. import android.provider.ContactsContract.RawContacts;  
  18. import android.view.View.OnClickListener;       
  19. import android.widget.Button;   
  20. public class HelloCursor extends ListActivity {  
  21.     private static String[] PROJECTION = new String[] { Contacts._ID,  
  22.             Contacts.DISPLAY_NAME };  
  23.   
  24.     /** Called when the activity is first created. */  
  25.     @Override  
  26.     public void onCreate(Bundle savedInstanceState) {  
  27.         super.onCreate(savedInstanceState);  
  28.         setContentView(R.layout.main);  
  29.         Cursor c = getContentResolver().query(Contacts.CONTENT_URI, PROJECTION,  
  30.                 nullnull, Contacts.DISPLAY_NAME + " COLLATE NOCASE");  
  31.         startManagingCursor(c);  
  32.         MyCursorAdapter adapter = new MyCursorAdapter(this, R.layout.list_row,  
  33.                 c);  
  34.         this.setListAdapter(adapter);  
  35.         Button button = (Button)findViewById(R.id.Button01);   
  36.         OnClickListener listener=new OnClickListener(){  
  37.             @Override      
  38.             public void onClick(View v) {       
  39.                 doAction();       
  40.             }           
  41.         };  
  42.         button.setOnClickListener(listener);  
  43.         mHandler = new Handler();  
  44.          
  45.     }  
  46.   
  47.     private String[] mStrings = { "hubin""hudashi""robin" };  
  48.     int cnt = 0;  
  49.      private Handler mHandler;  
  50.       
  51.     class AddContactThread implements Runnable {  
  52.         public void run() {  
  53.             int nStringLength = mStrings.length;  
  54.             int randomNumber = 0;  
  55.             ContentValues newValues = new ContentValues();  
  56.             String tempString = null;  
  57.             randomNumber = (int) (Math.random() % 10);  
  58.             for (int i = 0; i < nStringLength; i++) {  
  59.                 tempString = mStrings + cnt + randomNumber;  
  60.                 newValues.put(Contacts.DISPLAY_NAME, tempString);  
  61.                 getContentResolver().insert(RawContacts.CONTENT_URI, newValues);  
  62.                 newValues.clear();  
  63.   
  64.             }  
  65.             cnt++;  
  66.         }  
  67.     }  
  68.     AddContactThread addContact=new AddContactThread();  
  69.     void doAction()  
  70.     {  
  71.          mHandler.post(addContact);  
  72.     }  
  73. }  
  74. class MyCursorAdapter extends CursorAdapter {  
  75.     Context  context=null;  
  76.     int viewResId;  
  77.     public MyCursorAdapter(Context context, int resource, Cursor cursor) {  
  78.         super(context,cursor);  
  79.         viewResId=resource;  
  80.     }  
  81.     public View newView(Context context, Cursor cursor, ViewGroup parent) {  
  82.           
  83.         TextView view =null;  
  84.        LayoutInflater vi = null;  
  85.        vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
  86.        view =(TextView)vi.inflate(viewResId, parent, false);  
  87.            //v =(TextView)vi.inflate(textViewResourceId,null);  
  88.        Log.i("hubin","newView"+view);  
  89.         return view;  
  90.     }  
  91.     @Override  
  92.     public void bindView(View view, Context context, Cursor cursor) {  
  93.         Log.i("hubin","bind"+view);  
  94.         TextView nameView = (TextView) view;  
  95.         // Set the name  
  96.         nameView.setText(cursor  
  97.                 .getString(cursor.getColumnIndex("DISPLAY_NAME")));  
  98.     }  
  99. }</span>  


附1:关于newView和bindView一测试结果
newView android.widget.TextView@43b98ea0
bind android.widget.TextView@43b98ea0
newView android.widget.TextView@43b99948
bind android.widget.TextView@43b99948
newView android.widget.TextView@43b9a3f0
bind android.widget.TextView@43b9a3f0
add
bind android.widget.TextView@43b9a3f0
bind android.widget.TextView@43b99948
bind android.widget.TextView@43b98ea0
newView android.widget.TextView@43b9c5b0
bind android.widget.TextView@43b9c5b0
newView android.widget.TextView@43b9d058
bind android.widget.TextView@43b9d058
newView android.widget.TextView@43b9db00
bind android.widget.TextView@43b9db00



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值