对于更大的APP项目,我需要使用SQLite数据库。如果我的代码有效,我不会返回任何数据。我想我只是不理解光标对象。在此代码中,我只想取回一个名字,但是我的光标未正确初始化,但是我从Android开发人员那里获得了基本代码。所以我无法弄清楚为什么它不起作用。
public String getVorname (String nachname) {
SQLiteDatabase db = this.getReadableDatabase();
String[] projection = {ListeNamen.VORNAME};
String selection =ListeNamen.NACHNAME+" = ?";
String[] selectionArgs ={nachname};
String sortOrder = ListeNamen._ID + " DESC";
Cursor cursor = db.query(ListeNamen.TABLE_NAME,projection,selection,selectionArgs,null,null,sortOrder);
cursor.moveToFirst();
String vorname =cursor.getString(cursor.getColumnIndex(ListeNamen.NACHNAME));
cursor.close();
return vorname;
}
我会将"Jan"作为字符串返回,但它向我显示此错误
java.lang.IllegalStateException: Couldn't read row 0, col -1 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.database.CursorWindow.nativeGetString(Native Method)
at android.database.CursorWindow.getString(CursorWindow.java:438)
at android.database.AbstractWindowedCursor.getString(AbstractWindowedCursor.java:51)
at com.example.mainaplikation.DBHelper.getVorname(DBHelper.java:58)
at com.example.mainaplikation.MainActivity$1.onClick(MainActivity.java:29)
有了这个:
String[] projection = {ListeNamen.VORNAME};
定义希望查询选择的列。
所以你只需要列ListeNamen.VORNAME
.
但有了这个:
String vorname =cursor.getString(cursor.getColumnIndex(ListeNamen.NACHNAME));
您尝试检索结果中不存在的列ListeNamen.NACHNAME
。
通过变量的名称vorname
我猜你想做:
String vorname =cursor.getString(cursor.getColumnIndex(ListeNamen.VORNAME));
但由于结果中只有 1 列,您也可以执行以下操作:
String vorname =cursor.getString(0);