gpt4 book ai didi

android - 我不能在 android sqlite 中使用 MAX 函数

转载 作者:行者123 更新时间:2023-11-29 19:44:03 26 4
gpt4 key购买 nike

我在 dbhandler 类中构建了 max 函数,如下所示:

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

现在我想在 KEY_MESSAGE_ID 列中获得最大数量我在主要 Activity 中的代码如下:

int b = handler.getIDmax();
Toast.makeText(getApplicationContext(),""+b,Toast.LENGTH_LONG).show();

但是当我运行应用程序时它返回 0;有什么问题???

最佳答案

您错误地恢复了值(value),您得到的是列的索引,而不是值。

要获取值,调用

cursor.getInt(indexColumn)

您可以使用 getIndexColumn 或对该索引进行硬编码(对于该查询是安全的)

PS:一开始我不确定光标的位置,所以我会设置位置确定

cursor.moveToFirst()

编辑:这是我会怎么做(未测试)

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

关于android - 我不能在 android sqlite 中使用 MAX 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38147840/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com