How Do I Save And Read An Integer On Android Libgdx?
Solution 1:
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 someInteger
prefs.putInteger("score", 99);
//persist preferences
prefs.flush();
//getIntegerfrom preferences, 0is the default value.
prefs.getInteger("score", 0);
Solution 2:
There are different ways to do that:
- You can write to a
FileHandle
. Just create aFileHandle
likeGdx.files.local("myfile.txt");
and write to it usingfileHandle.writeString(Integer.toString(myInt));
Note, thatInternal
andClasspath
are read-only, so you can't write files there. Also note, that not all types of thegdx.files.
are usable for all backends. More on that here. The second way to do that are the Preferences. The
Preferences
are the only way to have persistent data for HTML5 applications. ThePreferences
are XML files in which you can store, read and change data. To createPreferences
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 Integer
s, myPref.putBoolean(("name", value)
for Boolean
s... 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.
Post a Comment for "How Do I Save And Read An Integer On Android Libgdx?"