如何将数组添加到偏好设置中(libGdx)

3

你好,我正在尝试从偏好设置文件中获取一个整数数组。

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

但是我没有保存的偏好设置。我尝试使用HashMap也不行。

2个回答

7

你不能将数组对象直接放入偏好设置中,但是你可以使用字符串来实现。所以你只需要在保存之前进行序列化,在从偏好设置中获取值后进行反序列化即可。

Libgdx支持通过提供JSON类来实现序列化。你应该遵循以下步骤:

    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格式的内容,请访问官方JSON网页


0

Preferences 只存储 String,因此您可以将 Array 序列化或将数组保存为索引和值对,如下所示:

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接