在我的Cursor初始化中找不到错误

问题描述 投票:0回答:1

对于更大的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)
android sqlite cursor android-sqlite illegalstateexception
1个回答
1
投票

有了这个:

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);
© www.soinside.com 2019 - 2024. All rights reserved.