您的位置:首页 > 移动开发 > Android开发

【Android开发】ListView使用CursorAdapter

2014-08-27 17:57 281 查看
<span style="font-family: Arial, Helvetica, sans-serif;">之前在ListView反映数据库查询数据的时候,由于还未搞懂CursorAdapter的用法,一直是把查询结果存在内存,内传参给extends BaseAdapter的类里面进行使用。今天刚刚使用了CursorAdapter,效果还不错,就把用法写出来,尽量简洁为主。</span>
第一步,先贴出onCreate()的代码

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_wish);
list_Wish=(ListView)findViewById(R.id.wishList);//获取这个Activity的布局里面的ListView,这里Activity的XML就不贴,就是简单的一个ListView
//获取数据库连接
dbHelper=new MyDatabaseHelper(MyWishActivity.this,"myDB.db");//MyDataBaseHelper继承SpliteOpenHelper,Android数据库操作里面的基础这里不展开讲
SQLiteDatabase sql=dbHelper.getReadableDatabase();
cur=sql.rawQuery("select * from table_A", null);
startManagingCursor(cur);
cur.moveToFirst(); <pre name="code" class="java"> MyCursorAdapter <span style="font-family: Arial, Helvetica, sans-serif;">myAdapter=new MyCursorAdapter(MyWishActivity.this, cur);//关键</span> list_Wish.setAdapter(myAdapter);}


第二步,要设计每一个列listview里面的item样式,就要写一个xml(listview_item.xml),假设只有一个TextView
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/textFromDB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:textSize="32sp"
android:textStyle="bold"
android:layout_marginLeft="2dp"
android:layout_marginTop="2dp"/>
</RelativeLayout>第三步,要重写上面第一步出现过的MyCursorAdapter
public class MyCursorAdapter extends CursorAdapter {

Context context=null;
Cursor c;
private LayoutInflater mInflater;
public MyCursorAdapter(Context context, Cursor c) {
super(context, c);
// TODO Auto-generated constructor stub
this.context=context;
this.c=c;
mInflater=LayoutInflater.from(this.context);

}

@Override
public void bindView(View arg0, Context arg1, Cursor arg2) {
// TODO Auto-generated method stub
TextView tx=(TextView)arg0.findViewById(R.id.wishshopname);
tx.setText(arg2.getString(arg2.getColumnIndex("name")));//假设从数据库tableA里面取出name这个字段的值显示

}

@Override
public View newView(Context arg0, Cursor arg1, ViewGroup arg2) {
// TODO Auto-generated method stub

return mInflater.inflate(R.layout.listview_item.xml, arg2, false);//这里返回加载了第二步的xml的一个view对象
}

}基本上上述步骤完了,就大功告成了;
但是可能你在运行的时候会出现这么一个错误:java.lang.IllegalArgumentException: column '_id' does not exist

这样的话是因为使用cursorAdapter,数据库的TABLE里面必须要有一个叫做_id的字段,你就在自己的table里面最前面添加一个_id INTEGER primary key autoincrement

,就是自增ID,就可以运行。

还有一个重要的问题,就是如何刷新ListView?

cur.requery();//游标cur做了新操作之后(例如插入删除),做这步
myAdapter.changeCursor(cur);
myAdapter.notifyDataSetChanged();

即可更新ListView!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐