将数据库内容显示到listView-游标适配器
游标适配器的使用
/* 将sd卡上的数据库内容显示到listView上,需要读取sd卡权限 */ public class CursorAdapterActivity extends Activity { private ListView lvPersons; private Context context; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.context = CursorAdapterActivity.this; String path = Environment.getExternalStorageDirectory().getAbsolutePath() +"/person_db.db"; //直接打到指定路径的数据库 SQLiteDatabase db = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READWRITE); Cursor cursor = db.rawQuery("select * from person",null);//查询到所有数据 lvPersons = (ListView) findViewById(R.id.lv_persons); //实现自定义cursoradapter MyCrusorAdapter myCrusorAdapter = new MyCrusorAdapter(context, cursor); lvPersons.setAdapter(myCrusorAdapter); } //直接使用游标适配器 class MyCrusorAdapter extends CursorAdapter{ public MyCrusorAdapter(Context context, Cursor c) { super(context, c, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER); } /* 返回一个item的view (不绑定数据) * */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = View.inflate(context, R.layout.listview_item_person, null); return view; } /* 将数据绑定到item的view中 * */ @Override public void bindView(View view, Context context, Cursor cursor) { //找到listView的item控件 TextView tvName = (TextView) view.findViewById(R.id.tv_name); TextView tvAge= (TextView) view.findViewById(R.id.tv_age); //填充数据 tvName.setText(cursor.getString(cursor.getColumnIndex("name")) + "hhh"); tvAge.setText(cursor.getInt(cursor.getColumnIndex("age")) + ""); } } }
SimpleCursorAdapter的使用:
//打开已经存在的数据库 //获得路径 String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/person_db.db"; // String path, 数据库的文件路径 // CursorFactory factory, 游标工厂, null表示默认的 // int flags 权限 SQLiteDatabase.OPEN_READWRITE表示可读可写 SQLiteDatabase db = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READWRITE); //查询数据 Cursor cursor = db.query("person", null, null, null, null, null, null, null); lvPersons = (ListView) findViewById(R.id.lv_persons); //设置SimpleCursorAdapter // Context, // int, item布局的id // Cursor, 数据源 // String[], 列名的string数组 // int[] 布局文件中控件的id与上个参数的列名对应 SimpleCursorAdapter simpleCursorAdapter = new SimpleCursorAdapter(MainActivity.this, R.layout.listview_item_person,cursor, new String[]{"name","age"}, new int[]{R.id.tv_name,R.id.tv_age}); lvPersons.setAdapter(simpleCursorAdapter);