单击按钮时,我想从SQLite获取数据ID。不幸的是我的应用程序崩溃了。当我尝试从SQLite中检索数据ID时会发生这种情况。
logcat的
05-17 01:00:54.873 16093-16093/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
at android.database.AbstractCursor.checkPosition(AbstractCursor.java:424)
at android.database.AbstractWindowedCursor.checkPosition(AbstractWindowedCursor.java:136)
at android.database.AbstractWindowedCursor.getInt(AbstractWindowedCursor.java:68)
at com.example.tony.easyactivity.MainActivity$1.onClick(MainActivity.java:49)
第49行
int id = data.getInt(data.getColumnIndex("ID"));
非常感谢任何帮助。
我尝试过:
btnAddData.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean isInserted = myDb.insertData(editName.getText().toString());
if (isInserted) {
Cursor data = myDb.getID(editName.getText().toString());
int id = data.getInt(data.getColumnIndex("ID"));
Toast.makeText(getApplicationContext(), id + "", Toast.LENGTH_LONG).show();
}
else
{
myDb.addData(editName.getText().toString());
Toast.makeText(getApplicationContext(), "Not yet inserted ", Toast.LENGTH_LONG).show();
}
}
});
}
DatabaseHelper
public Cursor getID(String info) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery("Select ID from " + TABLE_NAME1 + " WHERE " + COL3 + "=?", new String[]{info});
return c;
}
public boolean insertData(String name) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("Select * from " + TABLE_NAME1 + " WHERE " + COL3 + "=?", new String[]{name});
if (c.getCount() > 0) {
return true;
} else
return false;
}
public void addData(String name) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv=new ContentValues();
cv.put(COL3, name);
db.insert(TABLE_NAME1, null, cv);
}
答案 0 :(得分:2)
您需要将Cursor移动到第一个条目,然后才能使用moveToFirst()
方法访问其数据。所以在onClickListener()
:
Cursor data = myDb.getID(editName.getText().toString());
data.moveToFirst();
int id = data.getInt(data.getColumnIndex("ID"));