Reputation: 139
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
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
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
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
Reputation: 42026
final String MY_QUERY = "SELECT MAX(_id) FROM organize";
try only this
Upvotes: 2