简单的例子说明一下,使用CursorAdapter读取数据库里,需要的数据,把它显示到listview上。
ListView数据来自数据库
CursorAdapter 继承了 BaseAdapter
好处:仅加载需要显示的数据,性能好
使用方法:
1.实现两个参数构造方法
2.重写newView()方法
layout->view
3.重写bindView()方法
view.set
数据更新:
adapter.changeCursor(cursor);
adapter.notifyDataSetChanged()
代码如下:
public class MySqliteOpenhelper extends SQLiteOpenHelper { public MySqliteOpenhelper(Context context, int version) { super(context, "dianhuaben.db", null, version); } @Override public void onCreate(SQLiteDatabase db) {//注意:使用CursorAdapter时,创建表必须有以_id为列名的列 String sql = "CREATE TABLE dhb (_id INTEGER PRIMARY KEY AUTOINCREMENT,name VARCHAR(20),phone VARCHAR(20))"; db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } }
使用CursorAdapter的代码如下:
public void createCursorAdapter(Cursor cursor) { //游标适配器,构造方法,传入cursor mAdapter = new CursorAdapter(this, cursor) {//重写两个方法 @Override public View newView(Context context, Cursor cursor, ViewGroup parent) {//找到布局和控件 ViewHolder holder = new ViewHolder(); LayoutInflater inflater = getLayoutInflater(); View inflate = inflater.inflate(R.layout.listview_item, null); holder.item_tv_name = (TextView) inflate.findViewById(R.id.item_tv_name); holder.item_tv_phone = (TextView) inflate.findViewById(R.id.item_tv_phone); inflate.setTag(holder); return inflate;//返回的view传给bindView。 } @Override public void bindView(View view, Context context, Cursor cursor) {//复用布局。 // 把数据设置到界面上 ViewHolder holder = (ViewHolder) view.getTag(); String name = cursor.getString(cursor.getColumnIndex("name")); String phone = cursor.getString(cursor.getColumnIndex("phone")); holder.item_tv_name.setText(name); holder.item_tv_phone.setText(phone); } }; };
另一种是使用SimpleCursorAdapter,简化了代码,同样达到如上的效果
SimpleCursorAdapter继承了CursorAdapter,用法类似SimpleAdapter。
代码如下:
public void createSimpleCursorAdapter(Cursor cursor) {// SimpleCursorAdapter继承了CursorAdapter继承了BaseAdapter String[] from = {TABLE_NAME_NAME,TABLE_NAME_PHONE};//列名与控件id一一对应 int[] to = {R.id.item_tv_name,R.id.item_tv_phone}; //用的是SimpleCursorAdapter,用法和simpleAdapter相似 mAdapter = new SimpleCursorAdapter(MainActivity.this, R.layout.listview_item, cursor, from, to); }
注意:使用SimpleCursorAdapter,时,创建表必须有以_id为列名的列