android:最终得分和高分

时间:2011-05-22 16:27:30

标签: android sql sqlite

在完成我的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的基本知识,ifnal得分/高分比较也会是小菜一碟。我想我用这个做了一个小鼹鼠。有更好的方法吗?

1 个答案:

答案 0 :(得分:3)

好吧,看起来你只保存了最高分 - 而不是所有分数,甚至是前n分。如果是这种情况,可能更容易将高分保存在共享偏好

public long getHighScore(){
SharedPreferences pp = PreferenceManager
            .getDefaultSharedPreferences(context);


if(score>pp.getLong("highscore",0l)){
    Editor pe=(Editor) pp.edit();
    pe.putLong("highscore",score);
    pe.commit();
    return score;
 } else {return pp.getLong("highscore",0l);}

}