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