После завершения моей игры для Android я хочу, чтобы пользователь сравнил свой балл с высоким баллом. Для этого я сохранил текущий рекорд в базе данных SQLite. Но я думаю, что мой метод (который, кажется, работает) неуклюж и уродлив:
//in the final score activity, which has been sent the users score from the game.
if (extras != null){
//get users score
SCORE = extras.getLong("Score");
//create DB if necessary, otherwise open
startDatabase();
/tv is a text view (defined outside this code snippet)
tv.setText("Your score: "+SCORE+" \n"+"Top Score: "+ getHighScore());
}
}
//opens or creates a DB. If it is created insert current score.
public void startDatabase(){
SQLiteDatabase myDB = null;
try{
myDB = this.openOrCreateDatabase(DB_NAME, 0,null);
myDB.execSQL("CREATE TABLE IF NOT EXISTS "
+ SCORE_TABLE
+ " (key VARCHAR,"
+ " score NUM)");
}catch(SQLException e){
myDB.close();
}
Cursor c1 = myDB.rawQuery("SELECT * FROM "+ SCORE_TABLE ,null);
c1.moveToNext();
Long HIGHSCORE=0l;
//try to get current high score.
try{
HIGHSCORE = c1.getLong(c1.getColumnIndex("score"));
}
//DB score is empty. Fill it with current score. This is the initial high ` //score.
catch(IndexOutOfBoundsException e){
myDB.execSQL("INSERT INTO "+ SCORE_TABLE+"(score)
VALUES('"+SCORE+"')" );
myDB.close();
}
c1.close();
myDB.close();
}
Следующий метод извлекает текущий рекорд и, если необходимо, вводит новый рекорд.
//returns the high score. also inputs new score as high score if it is high enough.
public long getHighScore(){
SQLiteDatabase myDB = null;
myDB = this.openOrCreateDatabase(DB_NAME, 0,null);
Cursor c1 = myDB.rawQuery("SELECT * FROM "+ SCORE_TABLE ,null);
c1.moveToNext();
Long HIGHSCORE=0l;
try{
HIGHSCORE = c1.getLong(c1.getColumnIndex("score"));
}
catch(IndexOutOfBoundsException e){
}
//if user score is higher than high score...
if(HIGHSCORE<=SCORE){
myDB.execSQL("UPDATE "+ SCORE_TABLE+" SET score= '"+SCORE+"'" );
HIGHSCORE=SCORE;
myDB.close();
}
c1.close();
myDB.close();
return HIGHSCORE;
}
Мне не особо нравится код. Первоначально я думал, что сравнение ифнальных и высоких баллов было бы просто, даже с моими базовыми знаниями SQL. Я думаю, что сделал из этого крота из горной мухи. Есть ли лучший способ сделать это?