Cursor類注意
最近做一個Android小項目的過程中用到數據庫操作,在查詢的時候老是出錯,代碼如下:
Cursor c=DB.query(TableName, null, selection, selectionArgs, null, null, null);
if(c!=null){
c.moveToNext();
Integer id=c.getInt(c.getColumnIndex("id"));
String Info=c.getString(c.getColumnIndex("Info"));
}
後來查看了源碼才知道 返回的對象指向一條元素的前一個位置(return A {@link Cursor} object,which is positioned before the first entry),應先進行moveToNext(),而moveToNext()返回一個boolean值,故將代碼改爲如下問題解決:
Cursor c=DB.query(TableName, null, selection, selectionArgs, null, null, null);
if(c.moveToNext()){
Integer id=c.getInt(c.getColumnIndex("id"));
String Info=c.getString(c.getColumnIndex("Info"));
}