简体   繁体   中英

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.

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

Preferences only stores String s so you could serialize the Array or save the array as pairs of index and values like this:

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

for (int x = 0; x<ints.length; x++){
   pref.put(Integer.toString(x),Integer.toString(ints[x]));
}

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