Preferences in libgdx

Yeah, you can use that now. Nighlies are building. To fetch a Preferences instance do this:

Note that the name must be useable as a file name. On Android we wrap SharedPreferences. On the desktop we write a Properties XML file to user/preferences-name (“my-preferences” above). That’s not perfect and it’s why we didn’t want to implement that in the first place (Java Preferences are not a solution either…).

Once you have that you can put and get booleans, ints, longs, floats and strings (will be stored as UTF-8).

To make sure your changes are actually persisted you can use

That’s really only relevant on the desktop. If your app terminates due to a severe error the mechanism persisting the thing might not get invoked (no its not a finalizer, but something similar). Flush will immediately persist the current preferences state. So its good practice to call this after you changed your preferences.

That’s it. Enjoy.

  • Adam

    Hooray! 😀

    I’ve been waiting on this to implement my options menu 🙂

    Though it is I suppose, less than ideal to save to the user dir on PCs, but good enough IMO.

  • Mario

    the problem on the PC is that the app could be run as a webstart or applet. in which case we don’t have the notion of an app relative directory. It should work in 90% of the cases though. Open for suggestions!

  • Ruben

    hi, why not adding some support to define a category, or name or whatever than on the pc was used as the app directory, so you can store the preferences as user/appname/my-preferences

    p.s. libgdx rocks

  • Mario

    that’s indeed a good idea. i’ll consider it.

  • Nilax

    I’m having a bit of trouble with this.

    On the deskrop everything works nicely, but when trying it on my phone it doesn’t seem to save. What might be wrong? I’m flushing it after changing preferences.

  • carl

    I’m having the same problem Nilax reported, do preferences save on the phone?

  • andzg

    I have the same issue. everything is fine on pc, but it can not save on the android device. Where exatcly should I look for the preference file?

  • Micah

    On desktop, can we get the file to respect the XDG Base DIR specification from

  • Blemma

    I also have the same problem in a Galaxy S. Any idea to solve it?

    Thanks in advance

  • David Dimalanta

    Is this the way to save and load the game automatically? Can you site me more examples, please?

  • Zhuinden

    Same problem on Nexus 7. Even after flushing, setting “true” to a specific boolean key leaves that specific boolean key as “false”. Switching to local file for preference serialization instead.

  • Zhuinden

    Nevermind. The error was that you can get only ONE instance of the Preferences, possibly due to the wrapper sending the Application as a parameter for the SharedPreferences. I guess I was the one at fault!