使用 ContentProvider 与 Sqlite 数据库过程中,获取 Cursor 对象之后,可以遍历数据库。
当前数据库里面的数据

第一列:_id
第二列:name
第三列:gender
说明,下面的查询结果均是按降序排列。
1. moveToNext
- Cursor c = getContentResolver().query(UserTableData.CONTENT_URI,
- null, null, null, null);
- if (c != null) {
- int nameIndex = c.getColumnIndex("name");
- while (c.moveToNext()) {
- System.out.println(c.getString(nameIndex));
- }
- }
查询结果

2. moveToFirst
- Cursor c = getContentResolver().query(UserTableData.CONTENT_URI,
- null, null, null, null);
- if (c != null && c.moveToFirst()) {
- int nameIndex = c.getColumnIndex("name");
- while (c.moveToNext()) {
- System.out.println(c.getString(nameIndex));
- }
- }
查询结果

可以看出少了一条记录,显然不对!
问题出在 c.moveToFirst
c.moveToFirst 将当前 Cursor 指向第一行数据,
那么 c.moveToNext 调用之后,当前 Cursor 指向第二行数据。
这样,第一条记录就被漏掉了!
修改代码
- Cursor c = getContentResolver().query(UserTableData.CONTENT_URI,
- null, null, null, null);
- if (c != null && c.moveToFirst()) {
- int nameIndex = c.getColumnIndex("name");
- while (!c.isAfterLast()) {
- System.out.println(c.getString(nameIndex));
- c.moveToNext();
- }
- }
ok!
3. for 循环
- Cursor c = getContentResolver().query(UserTableData.CONTENT_URI,
- null, null, null, null);
- if (c != null && c.moveToFirst()) {
- int nameIndex = c.getColumnIndex("name");
- for(;!c.isAfterLast();c.moveToNext()) {
- System.out.println(c.getString(nameIndex));
- }
- }
同样的查询结果

附录:Cursor 与数据库

来源:http://blog.youkuaiyun.com/androidbluetooth/article/details/7791287
本文介绍了在使用ContentProvider与SQLite数据库时,如何正确遍历Cursor对象以获取所有数据记录的方法。针对不同的遍历方式,如使用moveToNext、moveToFirst及for循环等,详细解析了可能出现的问题,并给出了相应的解决方案。
1832

被折叠的 条评论
为什么被折叠?



