Matt
Matt

Reputation: 3912

Sorting SQLite table with "ORDER BY" - Android

I have a SQLite db for my highscores table. Currently I am having trouble checking if the new score makes the highscores and also sorting the highscores table.

When the game is over, Results.java is called.

Results.java

total_score = dh.calculateTotalScore(score, percentage);
low_score = dh.check(score, percentage, total_score);
if(total_score > low_score) {
    dh.delete(10);
    dh.insert(score, percentage, total_score);
} else {
    dh.insert(score, percentage, 9999999);
}
dh.sort();

All the methods being called in Results.java are coming from DatabaseHelper.java.

DatabaseHelper.java

public void sort() {
    db.rawQuery("SELECT * FROM " + DB_TABLE + " ORDER BY " + TOTAL_SCORE, null);
}

public long calculateTotalScore(long score, int percentage) {
    long i;
    return i = (percentage * 1000) + score;
}

public long check(long score, int percentage, long sum) {
    Cursor c = db.rawQuery("SELECT " + TOTAL_SCORE + " FROM " + DB_TABLE, null);
    long count = c.getCount();
    long low_score;
    if(count == 10) {
        c.moveToLast();
        low_score = c.getInt(c.getColumnIndex(TOTAL_SCORE));
        return low_score;
    } else {
        return count;
    }
}

public long insert(long score, int percentage, long total_score) {
    ContentValues values = new ContentValues();
    values.put(SCORE, score);
    values.put(PERCENTAGE, percentage);
    values.put(TOTAL_SCORE, total_score);

    return db.insert(DB_TABLE, null, values);
}

public void delete(int row) { 
    db.delete(DB_TABLE, RANK + "=" + row, null);
}

The output for TOTAL_SCORE is being displayed as follows:

What I desire is for the output to be in numerical order. Like this:

The order they are in above is (I think) just the order they were inserted into the db. No errors happen when the program runs and the program does not crash. More code can be provided if needed.

Upvotes: 0

Views: 4780

Answers (1)

CL.
CL.

Reputation: 180300

SELECT does not modify anything; your sort function has no effect. (The rawQuery function returns the sorted list of records, but you ignore it.)

You have to put the ORDER BY clause into the query that is used to display the scores.

Upvotes: 4

Related Questions