· 8 years ago · Aug 30, 2018, 03:18 PM
1android: final score and high score
2//in the final score activity, which has been sent the users score from the game.
3if (extras != null){
4 //get users score
5 SCORE = extras.getLong("Score");
6 //create DB if necessary, otherwise open
7 startDatabase();
8
9 /tv is a text view (defined outside this code snippet)
10 tv.setText("Your score: "+SCORE+" n"+"Top Score: "+ getHighScore());
11
12 }
13}
14
15//opens or creates a DB. If it is created insert current score.
16public void startDatabase(){
17 SQLiteDatabase myDB = null;
18
19
20 try{
21 myDB = this.openOrCreateDatabase(DB_NAME, 0,null);
22
23 myDB.execSQL("CREATE TABLE IF NOT EXISTS "
24 + SCORE_TABLE
25 + " (key VARCHAR,"
26 + " score NUM)");
27
28
29 }catch(SQLException e){
30 myDB.close();
31 }
32
33
34 Cursor c1 = myDB.rawQuery("SELECT * FROM "+ SCORE_TABLE ,null);
35
36 c1.moveToNext();
37
38
39 Long HIGHSCORE=0l;
40
41 //try to get current high score.
42 try{
43 HIGHSCORE = c1.getLong(c1.getColumnIndex("score"));
44 }
45
46 //DB score is empty. Fill it with current score. This is the initial high ` //score.
47 catch(IndexOutOfBoundsException e){
48 myDB.execSQL("INSERT INTO "+ SCORE_TABLE+"(score)
49 VALUES('"+SCORE+"')" );
50 myDB.close();
51
52 }
53
54 c1.close();
55 myDB.close();
56
57}
58
59//returns the high score. also inputs new score as high score if it is high enough.
60public long getHighScore(){
61 SQLiteDatabase myDB = null;
62
63 myDB = this.openOrCreateDatabase(DB_NAME, 0,null);
64
65 Cursor c1 = myDB.rawQuery("SELECT * FROM "+ SCORE_TABLE ,null);
66
67 c1.moveToNext();
68
69 Long HIGHSCORE=0l;
70 try{
71 HIGHSCORE = c1.getLong(c1.getColumnIndex("score"));
72 }
73 catch(IndexOutOfBoundsException e){
74
75
76
77 }
78
79 //if user score is higher than high score...
80 if(HIGHSCORE<=SCORE){
81 myDB.execSQL("UPDATE "+ SCORE_TABLE+" SET score= '"+SCORE+"'" );
82 HIGHSCORE=SCORE;
83 myDB.close();
84 }
85
86 c1.close();
87 myDB.close();
88 return HIGHSCORE;
89}
90
91public long getHighScore(){
92SharedPreferences pp = PreferenceManager
93 .getDefaultSharedPreferences(context);
94
95
96if(score>pp.getLong("highscore",0l)){
97 Editor pe=(Editor) pp.edit();
98 pe.putLong("highscore",score);
99 pe.commit();
100 return score;
101 } else {return pp.getLong("highscore",0l);}
102
103}