java - 如何将数组添加到首选项 (libGdx)

标签 java libgdx preferences

您好,我正在尝试获取保存在首选项文件中的整数数组。

    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()), "");

但是我保存了 0 个首选项。我也尝试过使用 HashMap。

最佳答案

您无法将数组对象放入首选项中,但是您可以使用字符串来完成此操作,因此您所需要做的就是在保存之前进行序列化,并在从首选项中获取值后进行反序列化。

Libgdx 通过提供 JSON 支持序列化类(class)。您应该遵循的是:

    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!

要了解有关 json 格式的更多信息,请访问 official json webpage

关于java - 如何将数组添加到首选项 (libGdx),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32998712/

相关文章:

iphone - 将 NSUserDefaults 转换为钥匙串(keychain)?

eclipse - 以编程方式获取 Eclipse 首选项值

java - ZK拖放和数据绑定(bind)

c# - 从头开始实现一棵树

java - 如何安装libgdx项目

java - libGDX 将我的系统从像素更改为单位

java - 尝试使用netbeans和mysql数据库向数据库中插入数据

java - 如何在java中处理xml内容中的标签

android-studio - libGDX - 导入到 android studio 的粒子效果工具

java - Android 偏好设置问题