我正在尝试一个简单的插入和读取操作,但我这样做时会遇到异常。
这是我正在尝试的代码,
try{
SQLiteDatabase db = openOrCreateDatabase("iTimeDB", MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS Activities (ID INTEGER PRIMARY KEY AUTOINCREMENT ,IMEI VARCHAR, Title VARCHAR, Time VARCHAR);");
db.execSQL("INSERT INTO Activities(IMEI, Title, Time) VALUES('"+ IMEI +"','"+ title +"','" +time+"');");
Cursor c = db.rawQuery("SELECT MAX(ID) FROM Activities", null);
c.moveToFirst();
String ID = c.getString(c.getColumnIndex("ID"));
Log.v("column: ID", ID);
db.close();
}
catch(Exception e)
{
e.printStackTrace();
Log.v("YYY", e.toString());
}
插入数据时没有异常,但是当我尝试从DB读取时,这是异常
这是LogCat
01-02 11:02:46.992: V/YYY(20510): java.lang.IllegalStateException: Couldn't read row
0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before
accessing data from it.
答案 0 :(得分:3)
试试这种方式
String ID = c.getInt(0);
OR
Cursor c = db.rawQuery("SELECT MAX(ID)'ID' FROM Activities", null);
c.moveToFirst();
String ID = c.getString(c.getColumnIndex("ID"));
答案 1 :(得分:0)
这可能是因为您的查询和光标过滤器
您的查询
Cursor c = db.rawQuery("SELECT MAX(ID) FROM Activities", null);
尝试
Cursor c = db.rawQuery("SELECT MAX(ID) as newID FROM Activities", null);
而不是String ID = c.getString(c.getColumnIndex("ID"));
使用String ID = c.getInt(c.getColumnIndex("maxID"));
答案 2 :(得分:0)
你应该总是检查游标是否能够使用api moveToFirst()来获取行。
if(c.moveToFirst())
{
String ID = c.getString(c.getColumnIndex("ID"));
Log.v("column: ID", ID);
}
db.close();