温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

学习笔记之CursorAdapter

发布时间:2020-10-02 05:22:08 来源:网络 阅读:497 作者:cpoopc 栏目:开发技术

CursorAdapter:通过该类可以用Cursor的方式访问数据库,并将查询出来的数据展示到列表视图(ListView)部件上。其中游标携带的结果集中必须有列名为“_id”的列,否则这个类无法工作。

sqlite查询获得Cursor,可以通过CursorAdapter将数据方便的显示在listview上.

使用方法:与BaseAdapter类似,需要重写CursorAdapter中的一些方法

下面用伪代码演示主要步骤:


CursorAdapter:

1.继承适配器:

class Myadapter extends CursorAdapter

2.构造函数://需要传入上下文,游标对象,用于遍历数据

public Myadapter(Context context, Cursor c) {

super(context, c);

}

2.newView():

inflate行布局

3.bindView()

在行布局中显示当前cursor所指向的数据


listview:

1.获得listview实例

ListView listview = findviewbyid(R.id.listview);

2.设置适配器

listview.setAdapter(myadapter);//cursor = db.query();

                               //myadapter = new Myadapter(this,cursor)


几点思考:

1.学完CursorAdapter后,想起之前学习BaseAdapter时候的优化,便想对其也进行优化,发现CursorAdapter中并没有convertview,而且其将getView分成了newView和bindView,百思不得其解.百度之后才发现,原来系统已经帮我们做了一步优化,其内部代码

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;
}

当convertView==null的时候才去调用newView.

2.如何获得id?

记得CursorAdapter要求我们必须以_id作为主键不?系统帮我们把_id通过getItemId()返回,再传递到一些对象方法中,如:

listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                db.delete("contact", "_id=?", new String[]{String.valueOf(id)});
                Cursor cursor = db.query("contact", null, null, null, null, null, null);
                myadapter.changeCursor(cursor);
                myadapter.notifyDataSetChanged();
                Log.e("id", id+"");
            }
        });

代码为删除listview点击行显示的表"contact"的数据.long id 即为系统帮我们传递过来的_id.这是通过getItemId()返回的,若要修改id,可以重写此方法.


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI