davidbain davidbain - 11 months ago 61
Android Question

Android SQLite incrementing a column value

I'm trying to create a score database that increments the players 'score' by one when they win by calling updateScore(). The primary key and player number are identical (I may need to restructure the DB at some point) and the final column is 'score'.

Below is the code that initially sets the score (this works), the method that gets the score (also works fine) and the method that updates the score, incrementing the relevant players score by 1. This is the part the doesn't work, is there something I should be doing differently here? Thanks.

/** Add a record to the database of two player scores
* @param playerId
* @param playerScore
public void addScore (int playerId, int playerScore) {

SQLiteDatabase database = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(ID, playerId);
values.put(PLAYERNUM, playerId);
values.put(SCORE, playerScore);

database.insert(TABLE_2PSCORES, null, values);



// Get the score
public int getScore (int playerId) {
SQLiteDatabase database = this.getReadableDatabase();

Cursor cursor = database.query(TABLE_2PSCORES, COLUMNS, " player = ?", new String[] {String.valueOf(playerId) }, null, null, null, null); //null = groupby, having, orderby, limit

if (cursor !=null) { cursor.moveToFirst(); }

int output = cursor.getInt(2);

return output;

// Increment score by 1
public void updateScore (int playerId) {

SQLiteDatabase database = this.getWritableDatabase();

int playerScore = getScore(playerId);
int playerScoreInc = playerScore ++;

ContentValues values = new ContentValues();
values.put("score", playerScoreInc);

database.update(TABLE_2PSCORES, values, PLAYERNUM+" = ?", new String[] {String.valueOf(playerId)} );



Answer Source


int playerScoreInc = playerScore ++;


int playerScoreInc = ++ playerScore;