我正在尝试将简单的Highscore保存到我的游戏中,但数据不会保存到共享首选项。
SharedPrefManager.java:
package com.divergent.thumbler;
import android.content.Context;
import android.content.SharedPreferences;
// all methods are static , so we can call from any where in the code
//all member variables are private, so that we can save load with our own fun only
public class SharedPrefManager {
//this is your shared preference file name, in which we will save data
public static final String MY_EMP_PREFS = "MySharedPref";
//saving the context, so that we can call all
//shared pref methods from non activity classes.
//because getSharedPreferences required the context.
//but in activity class we can call without this context
private static Context mContext;
// will get user input in below variables, then will store in to shared pref
private static int HighScore;
public static void Init(Context context)
{
mContext = context;
}
public static void LoadFromPref()
{
SharedPreferences settings = mContext.getSharedPreferences(MY_EMP_PREFS, 0);
// Note here the 2nd parameter 0 is the default parameter for private access,
//Operating mode. Use 0 or MODE_PRIVATE for the default operation,
settings.getInt("HighScore", HighScore);
}
public static void StoreToPref()
{
// get the existing preference file
SharedPreferences settings = mContext.getSharedPreferences(MY_EMP_PREFS, 0);
//need an editor to edit and save values
SharedPreferences.Editor editor = settings.edit();
editor.putInt("HighScore", HighScore);
//final step to commit (save)the changes in to the shared pref
editor.commit();
}
public static void DeleteSingleEntryFromPref(String keyName)
{
SharedPreferences settings = mContext.getSharedPreferences(MY_EMP_PREFS, 0);
//need an editor to edit and save values
SharedPreferences.Editor editor = settings.edit();
editor.remove(keyName);
editor.commit();
}
public static void DeleteAllEntriesFromPref()
{
SharedPreferences settings = mContext.getSharedPreferences(MY_EMP_PREFS, 0);
//need an editor to edit and save values
SharedPreferences.Editor editor = settings.edit();
editor.clear();
editor.commit();
}
public static void SetHighScore(int score)
{
HighScore = score;
}
public static int getHighScore()
{
return HighScore ;
}
}
我使用以下功能保存我的高分:
public void highscoreSaver() {
SharedPrefManager.LoadFromPref();
if(finalScore > SharedPrefManager.getHighScore()) {
SharedPrefManager.SetHighScore(finalScore);
SharedPrefManager.StoreToPref();
}
}
获得这样的高分:
HighScore = SharedPrefManager.getHighScore();
我做错了什么吗?请让我知道
答案 0 :(得分:0)
我认为问题在于settings.getInt("HighScore", HighScore);
根据文档here,SharedPreferences.getInt(String, int)
返回一个整数,第二个参数用于在给定键没有首选项时给出默认值,因此您应该执行类似HighScore = settings.getInt("HighScore", 0);
的操作