MrQweep
MrQweep

Reputation: 13

Convert SQLite Database to Java Arraylist

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.

Upvotes: 0

Views: 1439

Answers (2)

MrQweep
MrQweep

Reputation: 13

See the edit, I just kept adding Data to the Database, which I noticed when the length of the ArrayList kept going up. Let me just dig a hole and disappear in it.

Upvotes: 0

janos
janos

Reputation: 124844

But this doesn't return each mark of the specified subject once, but iterates through the table about 70-80 times.

I don't see evidence of iterating over the table multiple times. If that's what you're observing somehow, it's not in the posted code, but somewhere in the caller of this method.

In any case, I suggest improving the main loop in there, like this:

Cursor c = db.rawQuery(query, null);

while (c.moveToNext()) {
    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));
}
db.close();

Upvotes: 1

Related Questions