2

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

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
4

1 回答 1

1

您不能getColumnIndex对某些查询字符串执行操作,您需要传递 _id 列名。所以而不是

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

利用

 id = mCursor.getInt(mCursor.getColumnIndex("_id"));
于 2012-10-21T08:13:16.930 回答