Android 使用共享首选项进行高分保存
见鬼,我试图为我的项目取得高分,但我的代码只保存最后一个值,而不是最高值 如何仅存储最高值?这是我的密码 这是一个保存过程->Android 使用共享首选项进行高分保存,android,sharedpreferences,Android,Sharedpreferences,见鬼,我试图为我的项目取得高分,但我的代码只保存最后一个值,而不是最高值 如何仅存储最高值?这是我的密码 这是一个保存过程-> SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE); SharedPreferences.Editor editor = prefs.edit(); TextView outputV
SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
TextView outputView = (TextView)findViewById(R.id.textscore);
CharSequence textData = outputView.getText();
if (textData != null) {
editor.putString(TEXT_DATA_KEY, textData.toString());
editor.commit();
}
这就是阅读过程
SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
String textData = prefs.getString(TEXT_DATA_KEY, "No Preferences!");
TextView outputView = (TextView) findViewById(R.id.textread);
仅当共享首选项中的现有值小于新值时,才需要存储新值 您似乎没有在代码中检查此值
if (textData != null) {
editor.putString(TEXT_DATA_KEY, textData.toString());
editor.commit();
}
与
if(textData!=null){
if(Integer.parseInt(prefs.getString(TEXT\u DATA\u KEY,“0”))
您需要检查以前保存的值,以查看哪个值最高,否则您将只保存最新值,而不是最高值
例如
首先,为什么要将高位字符保存为字符串,请使用int或float(如果必须的话)
最简单的方法是在保存高分之前读取高分,并将其与您尝试保存的高分进行比较。您需要跟踪游戏中的高分。这是使用数字而不是使用文本视图的字符串最容易做到的:
int hiScore = 0;
在启动时,可能在onCreate()中,您希望获得以前的高分:
SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
try {
hiScore = prefs.getInt(HI_SCORE, 0);
} catch (NumberFormatException e) {
hiScore = 0;
}
if (newScore > hiScore) {
hiScore = newScore;
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(HI_SCORE, hiScore);
editor.commit();
}
当获得新分数时,如果高于先前的高分,则需要记录该分数:
SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
try {
hiScore = prefs.getInt(HI_SCORE, 0);
} catch (NumberFormatException e) {
hiScore = 0;
}
if (newScore > hiScore) {
hiScore = newScore;
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(HI_SCORE, hiScore);
editor.commit();
}
你似乎做得对,输出是什么?没有偏好?它正在保存最后一个值而不是最高值您需要检查以前保存的值以查看哪个值最高。您可能正在使用不同类型的值来记录分数,您需要相应地更改解析。Integer类型中的parseInt(String)方法不适用于参数(CharSequence)方法getInt(String,int)未为SharedReferences类型定义。Editor@Boldbayar您是对的,请使用prefs,因为它没有调用
.edit()
。我跳了一步。p、 你应该使用putInt()
而不是字符串将分数存储为int。我尝试过,但没有将其保存为int的选项。你能给我看吗D@Boldbayar请参阅我的编辑。使用putInt
行,而不是其上方的行。所以你是putin
而不是putString
应用程序正在崩溃,但是谢谢你的帮助:D