I would like to make a sql query and puts it in a TextView. I am able to do it for a ListView by following tutorials/examples on using adapters/dbHelpers. I am getting CursorIndexOutOfBoundException will leads me to believe I am not using the Cursor properly.
This is the code in onCreate:
TextView summaryTV = (TextView) findViewById(R.id.summary);
sumAllAmounts = iouHelper.getSumAllAmounts();
startManagingCursor(sumAllAmounts);
System.out.println(String.valueOf(iouHelper.getSumAllAmounts(sumAllAmounts)));
summaryTV.setText(String.valueOf(iouHelper.getSumAllAmounts(sumAllAmounts)));
sumAllAmounts is a Cursor which is returned by the database helper executing the sql command. I know the sql query is correct because I tested it using SQLite Database Browser. And I am able to get it to work on a ListView using ArrayAdapters.
The query should return 2 column: id and amount. The helper.getSumAllAmounts(Cursor) will return the second column Cursor.getInt(1) and it gets converted to a String to be displayed on the TextView. TextView.setText(String.valueOf(int))
Please guide me as to where I messed up. Thanks.
EDIT:
Code for DB helper function:
public Cursor getSumAllAmounts() {
return (getReadableDatabase().rawQuery("SELECT _id, SUM(amount) FROM ious", null));
}
public int getSumAllAmounts(Cursor c){
return (c.getInt(1));
}
Schema for the DB:
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE ious (_id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, type TEXT, amount INT, description TEXT, date String);");
}
Your bug is in
helper.getSumAllAmounts(Cursor). You are passing an invalid column index into a cursor.get* function. I’d need to see your query projection string and your calls to cursor.get* to tell you exactly what’s wrong.