Android 安卓:总分和高分
在完成我的Android游戏时,我希望用户将他/她的分数与高分进行比较。为此,我将当前的高分存储在SQLite数据库中。但我认为我的方法(似乎有效)既笨拙又丑陋:Android 安卓:总分和高分,android,sql,sqlite,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("Sco
//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;
}
//返回高分。如果新分数足够高,也将其输入为高分。
公共长线高分(){
SQLiteDatabase myDB=null;
myDB=this.openOrCreateDatabase(DB_名称,0,null);
游标c1=myDB.rawQuery(“从”+SCORE\u表中选择*为空);
c1.moveToNext();
长高分=0l;
试一试{
HIGHSCORE=c1.getLong(c1.getColumnIndex(“分数”);
}
catch(IndexOutOfBoundsException e){
}
//如果用户得分高于高分。。。
如果(HIGHSCORE那么,您似乎只保存了最高的分数,而不是所有的分数,甚至不是前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);}
}