我在网上找到了此代码示例,但无法正常工作。运行时,应用程序崩溃。有什么简单的解决方案吗?
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
最佳答案
您无法对某些查询字符串执行getColumnIndex
,需要传递列名_id。所以代替
id = mCursor.getInt(mCursor.getColumnIndex(MY_QUERY));
使用
id = mCursor.getInt(mCursor.getColumnIndex("_id"));