【问题标题】:Failing to query the maximum number in database table查询数据库表最大数失败
【发布时间】:2012-09-09 17:12:09
【问题描述】:

我正在尝试查询我的数据库以在我的区域表中查找最大“区域编号”以进行某种检查,但未成功,以便我可以将表单中的文本设置为下一个区域编号。

数据库表由四列组成; _id、inpsection_link、area_number、area-reference。

我在我的数据库助手类中创建了以下内容(使用这篇文章作为指导:SQLiteDatabase.query method):

 public int selectMaxAreaNumber (long inspectionId) {
    String inspectionIdString = String.valueOf(inspectionId);
    String[] tableColumns = new String[] { 
            AREA_NUMBER, 
            "(SELECT max(" + AREA_NUMBER + ") FROM " + AREAS_TABLE + ") AS max" 
        }; 
    String whereClause = INSPECTION_LINK + " = ?";
    String[] whereArgs = new String[] {
            inspectionIdString          
        };
    Cursor c = rmDb.query(AREAS_TABLE, tableColumns, whereClause, whereArgs, 
            null, null, null);
    int maxAreaNumber = c.getColumnIndex("max");
    return maxAreaNumber;
}

然后我在 areaEdit 类中调用如下:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    rmDbHelper = new RMDbAdapter(this);
    rmDbHelper.open();
    Intent i = getIntent();
    inspectionId = i.getLongExtra("Intent_InspectionID", -1);
    areaId = i.getLongExtra("Intent_AreaID", -1);
    if (areaId == -1) {
        nextAreaNumber = rmDbHelper.selectMaxAreaNumber(inspectionId) + 1;
        Toast.makeText(getApplicationContext(), String.valueOf(nextAreaNumber), 
                Toast.LENGTH_LONG).show();  
    }
    setContentView(R.layout.edit_area);
    setUpViews();
    populateFields();
    setTextChangedListeners();
}

但是,它每次只返回 1(即使有比数据库中存储的数字高的数字)。

Confused.com!!非常感谢任何帮助。

【问题讨论】:

    标签: android database sqlite max


    【解决方案1】:

    你的问题在这里:

    int maxAreaNumber = c.getColumnIndex("max");
    

    您将获得max 的列索引,即1,因为您的查询中只有一列。 相反,做这样的事情:

    int maxAreaNumber = 0;
    if(c.moveToFirst())
    {
        maxAreaNumber = c.getInt(1);
        // or cleaner
        maxAreaNumber = c.getInt(c.getColumnIndex("max"));
    }
    else
        // no data in cursor
    

    【讨论】:

    • 嗨 florianmski,感谢您的回复,但这不起作用 - 我收到 CursorIndexOutOfBoundsException: Index -1 requested, with a size of 4
    • @Scamparelli 我已经更新了我的答案,不要忘记 cursor.moveToFirst() 方法!
    • 非常感谢,除了表中没有数据时,现在似乎可以工作了。我想我需要测试 null,但它似乎不允许我 - 是否有替代 int 的方法?干杯。
    • @Scamparelli 一个好的做法是检查 c.moveToFirst() 是否返回 true,如果不是,则表示光标中没有数据,我再次更新了我的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多