2015-02-11 30 views
-1

我有這樣的代碼,獲取最後一個ID如何使用sqlite檢索單個結果?

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?

+0

發佈您的logcat – 2015-02-11 02:35:14

回答

1

這個錯誤的原因是你不檢查遊標是否爲空。

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

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

謝謝!繼承人我做了什麼 \t \t cursor.moveToFirst(); \t \t last = Integer.parseInt(cursor.getString(0)); – user3517855 2015-02-11 03:12:05

1

確保您在表格中有值。如果它沒有,它將最終與您的代碼異常。

請嘗試在您的代碼中執行此更改。

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