Android and SQLite - get maximum id from table

I am trying to create a method to extract the maximum id from my table, but I have problems.

This is my method. It works, but the return value is 0,

public int getLastId() { openDB(); int id = 0; final String MY_QUERY = "SELECT MAX(_id) AS _id FROM organize"; Cursor mCursor = mDb.rawQuery(MY_QUERY, null); try { if (mCursor.getCount() > 0) { mCursor.moveToFirst(); id = mCursor.getInt(mCursor.getColumnIndex(MY_QUERY)); } } catch (Exception e) { System.out.println(e.getMessage()); } finally { closeDB(); } return id; } 

I can fix this problem, thanks a lot

+7
source share
4 answers

Rewrite this line

 id = mCursor.getInt(mCursor.getColumnIndex(MY_QUERY)); 

in

 id = mCursor.getInt(mCursor.getColumnIndex("_id")); 

or better

 id = mCursor.getInt(0);//there only 1 column in cursor since you only get MAX, not dataset 

And look at LogCat, it will tell you about your problem.

+6
source
 final String MY_QUERY = "SELECT MAX(_id) FROM organize"; 

try only this

+2
source

Do you verify that the code inside the try block works fine?
Maybe the code jumps to the catch block, and id returns 0 that you initialized.

+1
source

Try this method:

 private int getMaxID(){ int mx=-1; try{ db = this.getReadableDatabase(); SQLiteDatabase db=this.getReadableDatabase(); Cursor cursor=db.rawQuery("SELECT max(ID) from tblIntents ",new String [] {}); if (cursor != null) if(cursor.moveToFirst()) { mx= cursor.getInt(0); } // cursor.close(); return mx; } catch(Exception e){ return -1; } } 
+1
source