Question

How do I save an integer that can be overwritten and then read it on android? I am using libgdx. I know how to do it for my desktop, but I want internal storage.

Was it helpful?

Solution

You should use libgdx Preferences.

That way it will work cross-plattform! (including Android)

Since you just want to store some Integer that should be just what you need.

See example:

//get a preferences instance
Preferences prefs = Gdx.app.getPreferences("My Preferences");

//put some Integer
prefs.putInteger("score", 99);

//persist preferences
prefs.flush();

//get Integer from preferences, 0 is the default value.
prefs.getInteger("score", 0);

OTHER TIPS

There are different ways to do that:

  1. You can write to a FileHandle. Just create a FileHandle like Gdx.files.local("myfile.txt"); and write to it using fileHandle.writeString(Integer.toString(myInt)); Note, that Internal and Classpath are read-only, so you can't write files there.
    Also note, that not all types of the gdx.files. are usable for all backends. More on that here.
  2. The second way to do that are the Preferences. The Preferences are the only way to have persistent data for HTML5 applications.
    The Preferences are XML files in which you can store, read and change data. To create Preferences for your app you just need to call:

    Preferences myPref = Gdx.app.getPreferences("PreferenceName");

Note, that you should use the full name, for example com.stackoverflow.preferences, as on desktop all Preferences use the same file.
To write data you can use myPref.putInteger("name", value) for Integers, myPref.putBoolean(("name", value) for Booleans... Make sure you call myPref.flush() after all changes, to save the new data.
To get the data you can call myPref.getInteger("name, defaultValue"). The default value is returned if there is no data with the given name. More on Preferences here.

Hope i could help.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top