如何获得Max值SQLite Android

时间:2015-09-29 18:56:14

标签: android sqlite

尝试在TABLE_GOALS中获取最大ID

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();

}

我无法获得最大价值而且我不知道为什么。对不起,这是Android中的新手。

2 个答案:

答案 0 :(得分:2)

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;

}

答案 1 :(得分:1)

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