Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a array to preferences (libGdx)

Hello I've trying to get a array of integers saved in a Preferences file.

    int[] ints = {2, 3, 4};

    Hashtable<String, int[]> hashTable = new Hashtable<String, int[]>();
    hashTable.put("test", ints);

    pref.getPref().put(hashTable);
    pref.getPref().flush();

    Gdx.app.log(String.valueOf(pref.getPref().get()), "");

But I got 0 saved prefs. I did try it with HashMap too.


1 Answers

you cannot put the array object into preferences however you can do it with string so all you need is to serialize before saving and deserialize after getting the value from preferences.

Libgdx supports serialization by delivering JSON class. What you should follow is:

    Hashtable<String, String> hashTable = new Hashtable<String, String>();

    Json json = new Json();

    hashTable.put("test", json.toJson(ints) ); //here you are serializing the array

    ... //putting the map into preferences

    String serializedInts = Gdx.app.getPreferences("preferences").getString("test");
    int[] deserializedInts = json.fromJson(int[].class, serializedInts); //you need to pass the class type - be aware of it!

To read more about json format visit the official json webpage

like image 131
m.antkowicz Avatar answered Dec 08 '25 15:12

m.antkowicz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!