Adding persistence

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 ...

Get Android Game Programming by Example now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.