Reputation: 3
My Cursor is always -1 when i send a request to my database (sqlite) to load an image.
public Cursor getData(int id){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME + " WHERE ID = " + id;
Log.d(TAG, query);
Cursor data = db.rawQuery(query, null);
return data;
}
The result is an app crash and this log in the logcat:
FATAL EXCEPTION: main Process: com.master.tobias.phono, PID: 10721 android.database.CursorIndexOutOfBoundsException: Index -1 requested, with a size of 1
Edit: The query works fine with the DB Browser for SQLite.
Upvotes: 0
Views: 37
Reputation: 1048
It's also beneficial to look at the Android documentation of methods as it provides more information as to what the method if expecting as parameters and will be returning. Firstly, the db.rawQuery
Runs the provided SQL and returns a Cursor over the result set.
SQLiteDatabase
As for the cursor, you need to check the existence of an object with the Cursor variable. This can be done via using the following method:
cursor.moveToFirst();
Move the cursor to the next row.
This method will return false if the cursor is already past the last entry in the result set.
Cursor
This method will return a boolean which you can use for further validation. If the boolean is false, the cursor doesn't contain any data/objects within. If it's true, you know you have existence of the data.
Therefore, you are missing this functionality where you'll need to move the object to the first row which will allow you to determine if the query was empty or not.
Upvotes: 0
Reputation: 668
try this one
public Cursor getData(int id){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_NAME + " WHERE ID = " + id;
Log.d(TAG, query);
Cursor cursor= db.rawQuery(query, null);
while(cursor.moveToFirst()){
//get your value over here
}
return data;
}
Upvotes: 0