Reading Time: 2 minutes
So let’s start coding. 😉
Step 1 – Init the Preferences
Preferences are a simple way to store small data for your application, e.g. user settings, small game state saves and so on. Preferences work like a hash map, using strings as keys, and various primitive types as values.
To start working with Preferences, we are going to create an instance at the beginning of the TekiTutorial::class.
var prefs: Preferences? = null
In the create() method we will initialize the Preferences instance. For this, we have to figur out a name. In case, when we have more Preferences instances in the code, then we have to separate them from each other using the name.
We gonna use the name: myPreferences
prefs = Gdx.app.getPreferences(“myPreferences”)
Step 2 – Save the username
The next step is to save the changed username to the prefs. In the very last chapter we have implemented the feature to change the username. Inside the touchUsernameButton() method, when the user clicks on the OK button in the pop up window, in the code the input() method will be called. There we have already a log message and we reset the usernameText also.
To save a variable to the Preferences, we need a key. It should be a string. In the next step we are going to us it, to get back the value of the saved variable, in our case to get back the saved username.
The key gonna be the “currentUser”. In the first line the text string variable contains the new username. This is the only argument of the method input().
The flush() method will save the value.
Step 3 – Get back the username
Every time, when we start the game, the stored value of the username has to be set to the usernameText. To do that we will use here the key, what have used to save the username. We have to call the getString() method on the prefs varaible.
For the getString() method we need the key (“currentUser”), and a default value. It is needed, when Android won’t find any stored data under this key. In our case it will be “Enter your username”. To use this is logical, because when the user has set the username, then it has to be stored, so the usernameText won’t be empty anymore.
The next line goes after the instantiation of the prefs variable.
usernameText = prefs!!.getString(
“Enter your username”)
Step 4 – Test
Run the app and test it.
If you have made everything correctly, then if you click on the Username button, and you change the username, and close it, and open it again, then the username you choose should appear.
If the game doesn’t work as it expected, then here is the whole source for this chapter and you can review your code.
I hope the description was understandable and clear. But if you have still questions, then leave me comments below! 😉
Have a nice a day! 🙂