您的错误明确表明您需要将 Set 对象传递给函数putStringSet()。如documentation 中所述。
考虑到这一点,我认为使用 SharedPreferences 来存储您的 HighScores 是一个坏主意。你会面临不同的问题。
第一选择:使用玩家名称作为键,我们只使用putString作为我们输入的值
public static void setHighScore(Context context, String name, int score) {
Set<String> scoreSet = new HashSet<String>();
scoreSet.add(String.valueOf(score));
SharedPreferences.Editor editor = getPreferences(context).edit();
editor.putString(name, scoreSet);
editor.apply();
}
这是一个非常糟糕的实现。因为关键是玩家姓名,所以很难找回你的分数。
第二选择:仅使用一个键并将所有分数存储在一个集合中
public static void setHighScore(Context context, String name, int score) {
SharedPreferences prefs = getPreferences(context);
Set<String> scoreSet = prefs.getStringSet("highScores"); //I use "highScores" as the key, but could be what you want
// You need to create a function that find the lower scores and remove it
removeLower(scoreSet);
scoreSet.add(name + ":" + String.valueOf(score)); //need to define a pattern to separate name from score
SharedPreferences.Editor editor = prefs.edit();
editor.putStringSet("highScores", scoreSet);
editor.apply();
}
这也不是一个好主意。因为你需要重新定义一个函数来找到较低的分数并将其删除。您还需要定义一个模式来存储名称 + 分数。然后你需要定义一个函数来读取分数以将名称与分数分开。
解决方案:
这里好的解决方案是使用数据库。偏好不是针对存储的数据设计的,而是针对偏好设计的。此外,数据库将提供轻松存储/检索/订购/等您的数据的功能。看看here