Issue
And for a bigger APP project I need to work with an SQLite database. If my code works I don't get any data back. And I think I just don't understand the cursor object. In this code I simply want to get a firstname back but it sasy that my cursor is not initialized correctly, but I got the basic code from Android developers. So I can't figure out why it doesn't work.
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;
}
I would get back "Jan" as a String but it shows me this Error
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)
Solution
With this:
String[] projection = {ListeNamen.VORNAME};
you define the columns that you want the query to select.
So you want only the column ListeNamen.VORNAME
.
But with this:
String vorname =cursor.getString(cursor.getColumnIndex(ListeNamen.NACHNAME));
you try to retrieve the column ListeNamen.NACHNAME
which does not exist in the results.
By the name of the variable vorname
I guess you want to do:
String vorname =cursor.getString(cursor.getColumnIndex(ListeNamen.VORNAME));
but since there is only 1 column in the results, you could also do:
String vorname =cursor.getString(0);
Answered By - forpas
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.