从Android SQLite数据库获取最大唯一ID无效

时间:2012-10-21 07:51:54

标签: java android sql sqlite

我在网上找到了这个代码示例,但我无法让它工作。当它运行时,应用程序崩溃。对此有什么简单的解决方案吗?

public long getMaxID() {
        int id = 0;
        final String MY_QUERY = "SELECT MAX(_id) AS _id FROM db_table";
        Cursor mCursor = mDb.rawQuery(MY_QUERY, null);  

              if (mCursor.getCount() > 0) {
                mCursor.moveToFirst();
                id = mCursor.getInt(mCursor.getColumnIndex(MY_QUERY));
              }

    return id;
        }

我的logcat错误似乎是:

10-21 07:48:32.704: E/AndroidRuntime(4023): Caused by: java.lang.IllegalStateException: get field slot from row 0 col -1 failed

1 个答案:

答案 0 :(得分:1)

您无法对某些查询字符串执行getColumnIndex,您需要传递_id的列名称。而不是

 id = mCursor.getInt(mCursor.getColumnIndex(MY_QUERY));

使用

 id = mCursor.getInt(mCursor.getColumnIndex("_id"));