我正在尝试使用以下代码从SQLite数据库中读取:
public List<DBEntry> getAllDBEntrys() {
List<DBEntry> DBEntrys = new ArrayList<DBEntry>();
Cursor cursor = database.query(DatabaseClass.TABLE_APPTS,
allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
DBEntry DBEntry = cursorToDBEntry(cursor);
DBEntrys.add(DBEntry);
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return DBEntrys;
}
private DBEntry cursorToDBEntry(Cursor cursor) {
DBEntry DBEntry = new DBEntry();
DBEntry.setId(cursor.getLong(0));
DBEntry.setName(cursor.getString(1));
DBEntry.setStartDate(new Date(cursor.getLong(2)));
DBEntry.setDueDate(new Date(cursor.getLong(3)));
DBEntry.SetPriority(cursor.getInt(4));
DBEntry.setDesc(cursor.getString(5));
DBEntry.SetCompletion(cursor.getInt(6)==1?true:false);
return DBEntry;
}
我收到此错误:
01-23 16:35:23.509: E/CursorWindow(14609): Failed to read row 0, column 6 from a CursorWindow which has 1 rows, 6 columns.
数据库已有一个条目,因为sqlite3实用程序显示:
sqlite> select * from ThingsToDo;
0|asdf|1358847122203|1359192722202|7|abcd|0
sqlite> .schema
CREATE TABLE ThingsToDo( _id integer primary key autoincrement,name text not null,start_date integer,due_date integer,priority integer,description text, completed integer);
CREATE TABLE android_metadata (locale TEXT);
我认为问题是_id列不算作列,因为cursor.getColumnCount()
函数返回6而不是7,因为当我移动到我的PC文件时sqlite3实用程序显示。
我怎样才能做到这一点?
答案 0 :(得分:1)
public List<DBEntry> getAllDBEntrys()
{
List<DBEntry> DBEntrys = new ArrayList<DBEntry>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_APPTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst())
{
do
{
DBEntry DBEntry = new DBEntry();
DBEntry .setID(Integer.parseInt(cursor.getString(0)));
DBEntry .setName(cursor.getString(1));
DBEntry .setPhoneNumber(cursor.getString(2));
// Adding to list
DBEntrys .add(DBEntry );
} while (cursor.moveToNext());
}
// return list
return DBEntrys ;
}