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();
If you are just going to save and display a particular number of records, may be you can use shared Preference itself like below:
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);
DELETE RECORD FROM MY_TABLE WHERE SCORE = MIN(EXISTING_HIGH_SCORES)
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 :
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 :
.
}