You may have noticed that the current fastest time is zero and can therefore never be beaten. The other problem is that every time the player quits the game the high score is lost. Now, we will load a default high score from a file. When a new high score is achieved, save it to the file. It doesn't matter if the player quits the game or even switches off their phone; their high score will remain.
First we need two new objects. Declare them as members of the TDView
class after the TDView
class declaration. The first is a SharedPreferences
object and the second is an Editor
object, which actually writes to the file for us:
private SharedPreferences prefs; private SharedPreferences.Editor editor;
We use prefs
first as we just want to attempt to load a high score if one exists. We will also initialize editor
ready for when we save our high score. We do this in the TDView
constructor:
// Get a reference to a file called HiScores. // If id doesn't exist one is created prefs = context...