CursorAdapter和AsyncQueryHandler的简易使用

CursorAdapter介绍


CursorAdapter继承于BaseAdapter,因为数据可以实时更新,主要用于和数据库打交道,通过Cursor的方式访问数据库,将结果显示在ListView的Item中。查询的时候必须要有个“_id”字段。


AsyncQueryHandler介绍

用一个子线程进行异步查询,查询完毕后通过onQueryComplete方法可以得到一个cursor


使用

继承CursorAdapter

package com.smartsms.adolpher.myapplication;

import android.content.Context;
import android.database.Cursor;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CursorAdapter;

public class TestAdapter extends CursorAdapter {

    public TestAdapter(Context context, Cursor c) {
        super(context, c);
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        return null;
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {

    }
}

继承CursorAdapter

package com.smartsms.adolpher.myapplication;

import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.database.Cursor;

public class SimpleQueryHandler extends AsyncQueryHandler {
    public SimpleQueryHandler(ContentResolver cr) {
        super(cr);
    }

    //此cursor是一部查询结束后返回的cursor
    @Override
    protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
        super.onQueryComplete(token, cookie, cursor);
        //将查询后得到的cursor替换原来的cursor
        ((TestAdapter)cookie).changeCursor(cursor);

    }
}

设置Adapter

package com.smartsms.adolpher.myapplication;

import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ListView lv = (ListView) findViewById(R.id.lv);

        //cursor先传入null,因为我们在AsyncQueryHandler查询完毕后可以得到一个cursor,之后再把null替换掉
        TestAdapter testAdapter = new TestAdapter(this, null);
        SimpleQueryHandler queryHandler = new SimpleQueryHandler(getContentResolver());
        //传入testAdapter替换里面的cursor
        queryHandler.startQuery(0, testAdapter, null, null, null, null, null);

        lv.setAdapter(testAdapter);
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值