Thursday, November 13, 2014

Using libGDX Preferences

Preferences are a great way to store certain data for your application, best example being user settings. Stuff like sound settings, best highscore, or whether or not to auto-login to some social media service is what Preferences are for.

Preferences data is stored in an xml file in the user's home directory. On Android preferences will survive app updates but are deleted if the app is uninstalled. Preferences should not be used to store complex game data like level information or game saves.

You should check the entry at libGDX wiki about them.

In my game I have a class called Settings that I use to store and handle my preferences. The class is loaded when the application is started and it looks something like this:
public class Settings {
 
 
 private Preferences prefs;
 
        // toggle sounds and music on/off
 private boolean sounds;
 private boolean music;
 
        // volume
 private int soundVolume;
 private int musicVolume;
 
        // best score
 private int highScore;

}

The constructor of Settings is shown after this paragraph. The important thing here to know is that that preferences are called with the getPreferences() method used in the code and that the name of the file that is looked is the one given as parameter. In the methods calling for certain data type of data, the first parameter is the name of the field in the xml file and the second one is the default value if no such field exists.
So, as you can see. The sounds and music are on at full volume by default and the high score is zero.
public Settings() {
       // get the preferences
       this.prefs = Gdx.app.getPreferences("MyGame-preferences");
       // get the sounds on or off, def on
       this.sounds = this.prefs.getBoolean("sounds", true);
       // get the music on or off, def on
       this.music = this.prefs.getBoolean("music", true);
       // get sound volume
       this.soundVolume = this.prefs.getInteger("soundVolume", 100);
       // get music volume
       this.musicVolume = this.prefs.getInteger("musicVolume", 100);
       // personal high score
       this.highScore = this.prefs.getInteger("highScore", 0);
}

In my game I can change and store the settings like this when user for example toggles the sounds on or off. Remember to call the flush() method or otherwise the changes you make won't be saved.
 public void setSounds(boolean b) {
  this.sounds = b;
  this.prefs.putBoolean("sounds", this.sounds);
  this.prefs.flush();
 }
I use the following kind of method every time about to play a sound in the game to check if the sounds are enabled or not:
 public boolean sounds() {
  return this.sounds;
 }
like this:
        if (this.settings.sounds() {
           // play the sound
        }
And that's it for this short post this time, see you next time.

No comments:

Post a Comment