SQLite or SharedPreferences for High Scores

2019-09-07 13:15发布

I am trying to write in a code in my game to save the score after the timer times out. I have my score and I have my timer. I've read a bit about SharedPreferences and SQLite. I know that I want to save the top 10 high scores, but SharedPreferences is best for just 1 score. I am trying to wrap my head around SQLite but I just cannot get it. Any chance someone could help me to figure out a line of code to save only the top 10 scores.

Heres my onFinish code:

public void onFinish() {
        textViewTimer.setText("00:000");
        timerProcessing[0] = false;

        /** This is the Interstitial Ad after the game */
        AppLovinInterstitialAd.show(GameActivity.this);

        /** This creates the alert dialog when timer runs out  */

        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(GameActivity.this);
        alertDialogBuilder.setTitle("Game Over");
        alertDialogBuilder.setMessage("Score: " + count);
        alertDialogBuilder.setCancelable(false);
        alertDialogBuilder.setNeutralButton("Restart", new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int id){
                Intent restartGame = new Intent(GameActivity.this, GameActivity.class);
                startActivity(restartGame);
                finish();
            }
        });

        alertDialogBuilder.setNegativeButton("Home", new DialogInterface.OnClickListener(){
            public void onClick(DialogInterface dialog, int id) {
                GameActivity.this.finish();             
            }

        });
        alertDialogBuilder.show();

2条回答
来,给爷笑一个
2楼-- · 2019-09-07 13:44

If you are just going to save and display a particular number of records, may be you can use shared Preference itself like below:

public class Highscore {
private SharedPreferences preferences;
private String names[];
private long score[];

public Highscore(Context context)
{
preferences = context.getSharedPreferences("Highscore", 0);
names = new String[10];
score = new long[10];

for (int x=0; x<10; x++)
{
names[x] = preferences.getString("name"+x, "-");
score[x] = preferences.getLong("score"+x, 0);
}

}

public String getName(int x)
{
//get the name of the x-th position in the Highscore-List
return names[x];
}

public long getScore(int x)
{
//get the score of the x-th position in the Highscore-List
return score[x];
}

public boolean inHighscore(long score)
{
//test, if the score is in the Highscore-List
int position;
for (position=0; position<10&&this.score[position]>score; 
position+
+);

if (position==10) return false;
return true;
}

public boolean addScore(String name, long score)
{
//add the score with the name to the Highscore-List
int position;
for (position=0; position<10&&this.score[position]>score; 
position+
+);

if (position==10) return false;

for (int x=9; x>position; x--)
{
names[x]=names[x-1];
this.score[x]=this.score[x-1];
}

this.names[position] = new String(name);
this.score[position] = score;

SharedPreferences.Editor editor = preferences.edit();
for (int x=0; x<10; x++)
{
editor.putString("name"+x, this.names[x]);
editor.putLong("score"+x, this.score[x]);
}
editor.commit();
return true;

}

}

Reference: http://osdir.com/ml/Android-Developers/2010-01/msg00794.html

However, it is better advisable to use a SQLite, since the scores can be sorted while fetching itself. You can use a simple algorithm as,

  • SELECT 'TRUE' WHERE CURRENT_SCORE > MIN(EXISTING_HIGH_SCORES);
  • If records are available, and number of existing high scores > 10, then DELETE RECORD FROM MY_TABLE WHERE SCORE = MIN(EXISTING_HIGH_SCORES)
  • INSERT CURRENT SCORE INTO THE DB.
查看更多
beautiful°
3楼-- · 2019-09-07 14:04

You can use the code given below to save any number of score and retrieve them. Create a new database helper class named, DatabaseHandler.java and add the following code in it.

To initialise the class in your activity, put the following line in your activity :

DatabaseHandler db = new DatabaseHandler(this);

Then to add value to db use, db.addScore(count);

To filter out just top ten scores from the db, u may change the query in get method to :

String selectQuery = "SELECT  * FROM " + TABLE_SCORE + "LIMIT 10";

.

public class DatabaseHandler extends SQLiteOpenHelper {

// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;

// Database Name
private static final String DATABASE_NAME = "game";

// Table name
private static final String TABLE_SCORE = "score";

// Score Table Columns names
private static final String KEY_ID_SCORE = "_id";
private static final String KEY_SCORE = "score_value";

public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_SCORE_TABLE = "CREATE TABLE " + TABLE_SCORE + "("
            + KEY_ID_SCORE + " INTEGER PRIMARY KEY AUTOINCREMENT,"
            + KEY_SCORE + " TEXT" + ")";

    db.execSQL(CREATE_SCORE_TABLE);

}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_SCORE);

    // Create tables again
    onCreate(db);
}

// Adding new score
public void addScore(int score) {

    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();

    values.put(KEY_SCORE, score); // score value

    // Inserting Values
    db.insert(TABLE_SCORE, null, values);

    db.close();

}

// Getting All Scores
public String[] getAllScores() {

    // Select All Query
    String selectQuery = "SELECT  * FROM " + TABLE_SCORE;

    SQLiteDatabase db = this.getWritableDatabase();
    Cursor cursor = db.rawQuery(selectQuery, null);

    // looping through all rows and adding to list

    int i = 0;

    String[] data = new String[cursor.getCount()];

    while (cursor.moveToNext()) {

        data[i] = cursor.getString(1);

        i = i++;

    }
    cursor.close();
    db.close();
    // return score array
    return data;
}

}

查看更多
登录 后发表回答