Reputation: 29
I built max function in dbhandler class as below:
@Override
public int getIDmax() {
int MAX =0;
SQLiteDatabase db = this.getReadableDatabase();
try{
String QUERY = "SELECT MAX(KEY_MESSAGE_ID) AS KEY_MESSAGE_ID FROM "+TABLE_NAME ;
Cursor cursor = db.rawQuery(QUERY,null);
MAX =cursor.getColumnIndex(KEY_MESSAGE_ID);
db.close();
return MAX;
}catch (Exception e){
Log.e("error",e+"");
}
return 0;
}
Now I want to get maximum number in KEY_MESSAGE_ID column my code in main activity is as below:
int b = handler.getIDmax();
Toast.makeText(getApplicationContext(),""+b,Toast.LENGTH_LONG).show();
But when I run application it return 0; what is the problem???
Upvotes: 1
Views: 300
Reputation: 14572
You made a mistake to recover the value, you are getting the index of the column, not the value.
To get the value, call
cursor.getInt(indexColumn)
You can use the getIndexColumn or hardcode this index (safe with this query)
PS : I am not sure of the position in the cursor at the beginning, so I would set the position to be sure with
cursor.moveToFirst()
Edit : Here is how I would do it (not tested)
@Override
public int getIDmax() {
int MAX = -1;
SQLiteDatabase db = this.getReadableDatabase();
try{
String QUERY = "SELECT MAX(_message_id) FROM "+TABLE_NAME ;
Cursor cursor = db.rawQuery(QUERY,null);
cursor.moveToFirst(); //Set the position to the beginning, current position is -1. You can check if there is something in the cursor since this return a boolean
MAX = cursor.getInt(0);
db.close();
}catch (Exception e){
Log.e("error",e+"");
}
return MAX;
}
Upvotes: 2