Android数据存储操作⑤Adapter之SimpleCursorAdapter

SimpleCursorAdapter与SimpleAdapter类似,使用SimpleCursorAdapter更适合绑定数据库的记录集,

在业务类中查询返回Cursor,然后将Cursor赋给SimpleCursorAdapter。

详细内容参考示例:

首先,在业务类PersonService中加入返回Cursor的方法getRawScrollData(),代码如下:

1 PersonService.java
2 public Cursor getRawScrollData(int startResult, int maxResult){
3 List<Person> persons = new ArrayList<Person>();
4 SQLiteDatabase database = databaseHelper.getWritableDatabase();
5 return database.rawQuery("select personid , name, age from person limit ?,?",
6 new String[]{String.valueOf(startResult),
7 String.valueOf(maxResult)});
8 }

然后在PersonActivity类中使用SimpleCursorAdapter绑定数据:

1 public class PersonActivity extends Activity {
2 /** Called when the activity is first created. */
3 private final static String TAG="PersonActivity";
4 private ListView listView;
5 private PersonService personService;
6 @Override
7 public void onCreate(Bundle savedInstanceState) {
8 super.onCreate(savedInstanceState);
9 setContentView(R.layout.main);
10 listView = (ListView)findViewById(R.id.personList);
11 personService = new PersonService(this);//得到业务类对象!
12 /* 使用SimpleCursorAdapter 绑定数据*/
13 Cursor cursor = personService.getRawScrollData(0, 10);//得到游标
14 SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
15 R.layout.personitem, cursor,
16 new String[]{"personid", "name", "age"}, new int[]{R.id.personid,
17 R.id.name, R.id.age});
18 listView.setAdapter(adapter);
34 }
35 });
36 }
37 }

运行之后会报错,提示column "_id"不存在,这是由于android中的Cursor必须要包含一个列名为”_id”,否则这个类将不会工作!

可以将业务类的第五行进行如下修改:

1 return database.rawQuery("select personid as _id, name, age from person
2 limit ?,?",
3 new String[]{String.valueOf(startResult),
4 String.valueOf(maxResult)});// 查询结果的”personid”列名改为“_id”


原文地址:https://www.cnblogs.com/leon19870907/p/1991880.html