Android 中查询数据库时,会使用到cursor类。从数据库查出来的每一行数据,就是一条cursor。每行数据的集合,组成了整个Cursor。
1.Cursor的常用方法
cursor.close();
cursor.getCount(); //返回行数
cursor.getColumnCount();//返回所有列的总数
cursor.moveToFirst();//移动光标到第一行
cursor.moveToNext()://移动光标到下一行
cursor.isAfterLast();//是否是最后一行
cursor.moveToPrevious();//移动光标到上一行
cursor.getColumnName(int columnIndex);//
2.cursor遍历
cursor的初始位置是-1,而数据是从0开始的,所有要先moveToFirst()。
Cursor cursor = context.getContentResolver().query(CONTENT_URI_SMS,new String[]{SmsUtil.Sms.MESSAGE_ID}),SmsUtil.Sms.THREAD_ID + "=?" , new String[] {threadId}, order);
if(cursor != null && cursor.getCount() != 0 && cursor.moveToFirst()){
try{
while(!cursor.isAfterLast()){
String messageId = cursor.getString(0);
cursor.moveToNext();
}
}catch(Exception e){
e.printStackTrace();
}finally{
if(cursor != null){
cursor.close();
}
}
}