Geeky Cat
Geeky Cat

Reputation: 61

How to get the Max value SQLite Android

Trying to get the maximum id in my TABLE_GOALS

public String getLatestGoal(){
    SQLiteDatabase db=dbhandler.getWritableDatabase();

    //columns
    Cursor cursor=db.query(MyDBHandler.TABLE_GOALS, null, "SELECT MAX("+MyDBHandler.COLUMN_ID+"))", null, null, null, null);
    StringBuffer buffer = new StringBuffer();
    while(cursor.moveToNext()){
        int index1=cursor.getColumnIndex(MyDBHandler.COLUMN_ID);
        String max_id=cursor.getString(index1);
        buffer.append(max_id);
    }
    return buffer.toString();

}

I can't get the maximum value and i don't know why. Sorry, newbie here in Android.

Upvotes: 1

Views: 3656

Answers (2)

user7641341
user7641341

Reputation: 209

public int getMaxid(){

    String selectQuery = "SELECT max(id) as id FROM customerentries";
    SQLiteDatabase database = this.getWritableDatabase();
    Cursor cursor = database.rawQuery(selectQuery, null);

    cursor.moveToFirst();

    int maxid = cursor.getInt(cursor.getColumnIndex("id"));

    return maxid;

}

Upvotes: 3

Deepak Goyal
Deepak Goyal

Reputation: 4907

public String getLatestGoal(){
  SQLiteDatabase db=dbhandler.getWritableDatabase();
  Cursor c = db.query(MyDBHandler.TABLE_GOALS, new String[]{"MAX("+MyDBHandler.COLUMN_ID+")"}, null, null, null, null, null);
  if(c.getCount()>0){
    c.moveToFirst();
    String max_id=c.getString(0);
    buffer.append(max_id);
  }
  c.close();
  db.close();
  return buffer.toString();
}

Upvotes: 2

Related Questions