Wrote a method to get a record on the specified id:

public NotesData getInboxItemByID(String id){ db = dbHelper.getReadableDatabase(); cursor = db.query(DataBaseContract.NotesData.TABLE_NAME, new String[] {DataBaseContract.NotesData._ID}, DataBaseContract.NotesData._ID + "=?", new String[] {id}, null, null, null); int idColInd = cursor.getColumnIndex(DataBaseContract.NotesData._ID); int dateAndTimeColInd = cursor.getColumnIndex(DataBaseContract.NotesData.COLUMN_DATETIME); int titleColInd = cursor.getColumnIndex(DataBaseContract.NotesData.COLUMN_TITLE); int noteTextColInd = cursor.getColumnIndex(DataBaseContract.NotesData.COLUMN_NOTE); NotesData notesData = new NotesData(cursor.getString(idColInd), cursor.getLong(dateAndTimeColInd), cursor.getString(titleColInd), cursor.getString(noteTextColInd)); dbHelper.close(); db.close(); return notesData; } 

The application crashes with this error:

 android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1 

First, I don’t understand how such an error arose: I didn’t ask directly -1 . Probably should have placed the cursor at the beginning before executing the query, but it was not initialized before the query.

  • In connection with your editing - the difference in methods is minimal . - pavlofff
  • Thank you for your reply and comment. I had another error - Failed to read row 0, column -1 from a CursorWindow which has 1 rows, 1 columns. , while the method for obtaining all records works correctly, that is, the table is full. While thinking about the wording of a new question. - Gleb
  • Which of the getColumIndex() methods returns -1, which means that columns with this name are not in the database or it is not included in the database selection (not all columns are received). regarding your request - you request only an ID column, without columns containing data. - pavlofff

1 answer 1

When receiving a sample, the cursor is not positioned on any record in this sample and the cursor pointer is in front of the first position, so it returns the current index (pointer position in the cursor) = -1. Before receiving data from the cursor, you need to set the position from which to take the data (a specific record) - moveToPosition() or, at the beginning, moveToFirst() . To iterate over a cursor with several entries, use the moveToNext() method — each new method call will move the cursor pointer to the next entry in the selection

 cursor = db.query(DataBaseContract.NotesData.TABLE_NAME, new String[] {DataBaseContract.NotesData._ID}, DataBaseContract.NotesData._ID + "=?", new String[] {id}, null, null, null); cursor.moveToFirst(); int idColInd = cursor.getColumnIndex(DataBaseContract.NotesData._ID); ... 

you need to move the pointer after the query is executed, before the query the cursor does not contain data and the pointer has nowhere to move in it in principle.