简体   繁体   中英

save data with preferences in libGDX

In My game project, I want to save some data of levels like coins, gams, ... etc with preferences interface.

I supposed In My Question here the data is the level number only. ........................................................................

1) If the player finish the level_1, this code called to save LEVEL_NUM_ .

preferences.putInteger("LEVEL_NUM_", getLevelNum());
preferences.flush();

The .prefs 's file :

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
    <properties>
    <entry key="LEVEL_NUM_">1</entry>
    <entry key="SCORE_">3225</entry>
    </properties>

2) If the player finish the level_2, this code called again to save LEVEL_NUM_ .

preferences.putInteger("LEVEL_NUM_", getLevelNum());
preferences.flush();

The preferences update the data ie replace the LEVEL_NUM_ 's data with a new LEVEL_NUM_ 's data.

The NEW .prefs 's file :

    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
    <properties>
    <entry key="LEVEL_NUM_">2</entry>
    <entry key="SCORE_">5995</entry>
    </properties>

I want to add the data (like stack) NOT replace the data. What I do ?

all you need is to keep your levels in some collection (like Array<>) and then save this collection to Preferences. You will need to cast this collection to String (there's no putArray() function or something like this) and the best idea is to jsonify it.

JSON is a file format (something like xml but much lighter) with good support from libgdx side. The code to achieve your goal is something like:

    FloatArray levels = new FloatArray();
    levels.add(5993);
    levels.add(5995);

    ...

    Preferences p = Gdx.app.getPreferences("SETTINGS");

    Json json = new Json();

    String levelsJson = json.toJson(FloatArray.class, levels);

    p.putString("levels", levelsJson);

now you've got you levels collection saved and all you have to do to get it back is:

    FloatArray levels = json.fromJson(FloatArray.class, p.getString("levels");

Regards, Michał

Another possible solution would be to store the score of each level in it's own Key/Value pair, where the Key is the level and the value is the score:

preferences.putInteger("LEVEL_NUM_" + getLevelNum(), getScore());
prefernces.flush();

And the preferences would look like this:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
   <entry key="LEVEL_NUM_1">3225</entry>
   <entry key="LEVEL_NUM_2">5995</entry>
</properties>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM