Using preferences to store game states and options

Being able to read and write both text and binary files in your Libgdx projects already gives you all the flexibility you will ever require to handle game saves and configuration files. However, binary files might not be very convenient to store key-value pairs.

Do not worry! Libgdx always keeps a hidden ace. If all you need is to store a set of key-value pairs to keep track of basic player progress or game settings, there is a small utility that will make your day. The Preferences class offers an extremely simple API for you to store things such as top scores, the desired music volume, and so on.

This brief recipe will show you how to use this utility to your advantage.

Getting ready

Very quickly, import the samples projects into your Eclipse workspace.

How to do it…

Every Preferences instance points to an internal file. Creating or loading an existing file is as easy as calling the getPreferences() method in the Application interface:

Preferences preferences = Gdx.app.getPreferences("preferences");

The string you need to pass through might be used to determine the filename, so make sure it is valid and unique (it depends on the platform implementation). A good idea is to use the current package or fully qualified class name:

Preferences preferences = Gdx.app.getPreferences(PreferencesSample.class.getName());

The entries stored in a Preferences instance are identified by unique keys, and the values can either be integers, floats, Booleans, strings, or longs. In order to add new values or modify existing ones, use one of the following methods:

void putBoolean(String key, boolean val)
void putFloat(String key, float val)
void putInteger(String key, int val)
void putLong(String key, long val)
void putString(String key, String val)

Reading previously stored values is equally straightforward; you only need to call the corresponding get method, supplying the desired key and an optional default value. If no default value is supplied, and the entry does not exist, a built-in default value will be returned:

boolean getBoolean(String key, boolean defValue) 
float getFloat(String key, float defValue) 
int getInteger(String key, int defValue) 
long getLong(String key, long defValue) 
String getString(String key, String defValue)

Adding an entry does not immediately result in the Preferences instance saving everything out to the filesystem; the new values stay in memory instead. In order to trigger a save-to-disk operation, you need to call the flush() method on said instance.

How it works…

After running PreferencesSample on the desktop, you will have a com.cookbook.samples.PreferencesSample file inside a .prefs folder in your user directory. The file is just XML and has a very basic schema:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
  <entry key="difficulty">10</entry>
  <entry key="effectsVolume">0.0</entry>
  <entry key="playerName">8</entry>
  <entry key="showTips">false</entry>
  <entry key="musicVolume">0.0</entry>
</properties>

There is no encryption whatsoever, which may not make Preferences suitable for more sensitive data such as private keys, sensitive user data, or game records that should be validated against a server (trophies, best scores, and so on). No one likes cheats!

Note

A workaround is to encrypt the stored keys and values.

There's more…

You can retrieve the whole set of options as an associative array indexed by strings and containing arbitrary objects through the following method:

Map<String, ?> get()

Similarly, you can push a whole batch of preferences into a Preferences instance through the following method:

void put(Map<String, ?> vals)

You might encounter a situation where an entry is no longer needed; to get rid of it, just call the following:

void remove(String key)

See also

When the Preferences class just does not cut it, you can discover how to deal with more powerful file formats in the following recipes:

  • The The XML parsing primer recipe
  • The JSON serialization and deserialization recipe
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.176.166