save data with preferences in libGDX

若如初见. 提交于 2019-12-08 08:57:34

问题


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 i.e. 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 ?


回答1:


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ł




回答2:


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>


来源:https://stackoverflow.com/questions/32239499/save-data-with-preferences-in-libgdx

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!