如何使用sqlite检索单个结果?

时间:2015-02-11 02:31:21

标签: android sqlite cursor

我有这个代码检索最后一个id

 public int retrieveLastId() {

            SQLiteDatabase db = this.getWritableDatabase();
            Cursor cursor = db.rawQuery("select "+ RECORDING_ID +" from " + DATABASE_TABLE + " ORDER BY "+ RECORDING_ID +" DESC LIMIT 1 ", null);


            int last = 0;
            last = Integer.parseInt(cursor.getString(0));
            Log.e("sfsdlkfjs dfl sd",cursor.getString(0));
            return  last;
        } 

但我收到错误android.database.cursorindexoutofboundsexception 如何正确返回最后一个ID?

2 个答案:

答案 0 :(得分:1)

这个错误原因是你不检查游标是否为空。

if (cursor.moveToFirst()) // Check your cursor has value?
   System.out.println(cursor.getString(0); 

cursor.close();    //you should realse cursor 

答案 1 :(得分:1)

确保表格中包含值。如果它没有,它将以您的代码结束异常。

尝试在代码中进行此更改。

Cursor cursor = database.rawQuery(selectQuery, null);if(cursor!=null && cursor.getCount()>0){cursor.moveToFirst()
    do{
        bankbalresult = cursor.getString(0);
    } while (cursor.moveToNext());}