user836807
user836807

Reputation: 139

Android and SQLite - retrieve max id from table

I am trying to create method to retrieve the max id from my table but I've problem.

This is my method. It's working, but 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;

}

can I fix this problem, thanks a lot

Upvotes: 7

Views: 10591

Answers (4)

ernazm
ernazm

Reputation: 9268

Rewrite this line

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

to

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

or better to

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

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

Upvotes: 7

zyz82
zyz82

Reputation: 171

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;
    }
}

Upvotes: 2

Priyank
Priyank

Reputation: 1174

Have you check that code inside a try block works perfectly?
May be code jumps into catch block and id returns 0 that you have initialized.

Upvotes: 1

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

try only this

Upvotes: 2

Related Questions