一般ListView都是用来显示列表的,一般列表的数据都是来自数据库的,因此我们这里假设前面已经实现了一个DBService类,里面存在pageCursorQuery(int offset,int length);
比如dbservice.pageCursorQuery(3,5);表示跳过3个记录,插入5条记录,返回Cursor;
pageCursorQuery实现代码如下,需要注意的是,查询语句的主键必须要重命名为“_id”,不然会报错。
public Cursor pageCursorQuery(int low,int high){ db = helper.getWritableDatabase(); Cursor cursor = db.query("person", new String[]{"id as _id","name","age"}, null, null, null, null, null,low+","+high); return cursor; }
package org.xiazdong.db; import org.xiazdong.db.service.DBService; import android.app.Activity; import android.database.Cursor; import android.os.Bundle; import android.widget.ListView; import android.widget.SimpleCursorAdapter; public class MainActivity extends Activity { private ListView listView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); listView = (ListView)this.findViewById(R.id.listview); DBService service = new DBService(this); Cursor cursor = service.pageCursorQuery(0, 10); SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.item,cursor, new String[]{"_id","name","age"}, new int[]{R.id.id1,R.id.name,R.id.age}); listView.setAdapter(adapter); } }
(1)前者是用Cursor表示数据,后者用List<Map<String,Object>>表示数据;
(2)前者的查询语句的主键必须要为"_id";