I have a table with the following
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL( "CREATE TABLE " TABLE_NAME " (" "ID" " INTEGER PRIMARY KEY,"
COLUMN_TOPIC " TEXT," COLUMN_LOCATION " TEXT)");
}
I am trying to get all the data at a given rowid
public void getRowCursor(int position){
SQLiteDatabase database = getWritableDatabase();
Cursor cursor = database.rawQuery("SELECT * FROM " TABLE_NAME " WHERE "
"ID" "=" String.valueOf(position), null);
cursor.moveToFirst();
cursor.close
//or
Cursor cursor = database.query(TABLE_NAME, null, "ID", new String[]{
String.valueOf(position)}, null, null, null, null );
cursor.moveToFirst();
cursor.close
database.close
}
I get an error
java.lang.IllegalArgumentException: Cannot bind argument at index 1 because the index is out of range. The statement has 0 parameters.
I did populate the table. How do I return a cursor based on the position of entry.
CodePudding user response:
How do I return a cursor based on the position of entry
First, your method getRowCursor()
should return a Cursor
.
Also, you should not close the returned cursor because I assume that you want to use its results somehow.
Your code with the method rawQuery()
should work like this:
public Cursor getRowCursor(int position) {
SQLiteDatabase database = getWritableDatabase();
String sql = "SELECT * FROM " TABLE_NAME " WHERE ID = " String.valueOf(position);
Cursor cursor = database.rawQuery(sql, null);
// cursor.moveToFirst();
return cursor;
}
But, the safe and recommended way to pass parameters to a query is with ?
placeholders instead of concatenating them inside the sql statement and passing them as array items in the 2nd argument of rawQuery()
:
public Cursor getRowCursor(int position) {
SQLiteDatabase database = getWritableDatabase();
String sql = "SELECT * FROM " TABLE_NAME " WHERE ID = ?";
Cursor cursor = database.rawQuery(sql, new String[] {String.valueOf(position)});
// cursor.moveToFirst();
return cursor;
}
Note that moveToFirst()
moves the cursor's index at the 1st row of the cursor (if it exists).
I commented out this call, because you should use it after you call getRowCursor()
like this:
Cursor cursor = getRowCursor(10); // or any other ID
if (cursor.moveToFirst()) { // the cursor contains at least 1 row
....
} else { // the cursor is empty
....
}
and when you are done with the cursor:
cursor.close();