I am learning how to uses databases on Android and i am trying a simple example in which i have two textboxes [brakes and rpm] when i enter values into those boxes and hit the “write button” it enters them into the database table “performance”. When i hit the “read” button it should query the table and print the contents but i get the following error while querying:
android.database.CursorIndexOutOfBoundsException: Index -1 re
quested, with a size of 0
Here is my relevant code:
private static final String KEY_ROWID = "_id";
private static final String KEY_BRAKES = "brakes";
private static final String KEY_RPM="rpm";
private static final String DATABASE_NAME = "MyDB2";
private static final String DATABASE_TABLE = "performance";
private static final int DATABASE_VERSION=1;
private static final String DATABASE_CREATE = "create table performance (_id integer primary key autoincrement, " + "brakes text not null, rpm text not null);";
//--insert an entry to the database--
public void insertData(String filter, String data){
ContentValues entry = new ContentValues();
if(filter.equals("b")){
entry.put(KEY_BRAKES, data);
Log.d(TAG,"inserted brake data");
db.insert(DATABASE_TABLE, null, entry);
}
else if (filter.equals("r")){
entry.put(KEY_RPM, data);
Log.d(TAG,"inserted rpm data");
db.insert(DATABASE_TABLE, null, entry);
}
}
//--retrive all entries
public Cursor getAllData(){
Log.d(TAG,"about to query");
try{
Cursor c = db.query(DATABASE_TABLE, new String[]{KEY_BRAKES,KEY_RPM}, null, null, null, null, null);
Log.d(TAG,"id=" + c.getString(0));
return c;
}catch(Exception e){
Log.d (TAG,"error");
Log.e(TAG,e.toString());
}
return null;
}
And the way that i enter items is as follows:
brakeRead = brakes.getText().toString();
rpmRead = brakes.getText().toString();
db.open();
db.insertData("b", brakeRead);
db.insertData("r", rpmRead);
db.close();
And the way i query is as follows:
db.open();
Cursor c = db.getAllData();
if(c.moveToFirst())
{
do{
output.append("id: " + c.getString(0) + " brakes: " + c.getString(1) + " rpm: " + c.getString(2));
}while(c.moveToNext());
}
db.close();
But i am getting this error while querying: android.database.CursorIndexOutOfBoundsException: Index -1 re
quested, with a size of 0
Can anyone see if i am doing something wrong?
Query is perfect to retieve data but you got error as listed below it means you have no record in your database, so i think there is something missing while inserting database
android.database.CursorIndexOutOfBoundsException: Index -1 re quested, with a size of 0