So I've been trying to convert content of a SQLite Database to Objects in an ArrayList. To do that, I've tried to iterate through the Table like written in the code below. But this doesn't return each mark of the specified subject once, but iterates through the table about 70-80 times. I think I know the problem, being that the c.moveToNext moves to the next column of the row and not the next row, but I don't know the solution to this.
public ArrayList<Marks> toMarksList(String subject){
ArrayList<Marks> marksArrayList = new ArrayList<Marks>();
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_MARKS + " WHERE " + COLUMN_SUBJECT + "=\"" + subject + "\";";
Cursor c = db.rawQuery(query, null);
c.moveToFirst();
while(!c.isAfterLast()){
if(c.getColumnIndex("subject")!=0){
String dbName = c.getString(c.getColumnIndex("name"));
Double dbValue = c.getDouble(c.getColumnIndex("value"));
Double dbWeight = c.getDouble(c.getColumnIndex("weight"));
marksArrayList.add(new Marks(subject, dbName, dbValue, dbWeight));
}
c.moveToNext();
}
db.close();
return marksArrayList;
}
This code seems to be seriously broken, because it also gets the wrong name for the third entry in the database, but onnly in the first half of the while loops. How do I make it so the cursor is at one row, reads the needed entries of that row and then continues to the next row?
EDIT: Turns out I'm completely stupid and kept adding new entries to the list every time I launched the app.
if(c.getColumnIndex("subject")!=0)there is no use of this line. alsoc.moveToNextdoes move to next row and not the next column. post your expected result and actual resultsc.moveToNext();moves to the next row, not the next column. Suggest examining the content ofTABLE_MARKSin the database to confirm there are no duplicate entries.