我正在Android工作室制作简单的记忆游戏。游戏包含2个活动(MainActivity,GameActivity),我需要从GameActivity中保存高分并在MainActivity中显示它。我已经尝试过使用SharedPreferences,但MainActivity中的高分仍为0。 这是我在GameActivity中的代码:
SharedPreferences prefs;
SharedPreferences.Editor editor;
String dataName = "MyData";
String intName = "MyInt";
int defaultInt = 0;
int hiScore;
prefs = getSharedPreferences(dataName,MODE_PRIVATE);
editor = prefs.edit();
hiScore = prefs.getInt(intName, defaultInt);
editor.putInt(intName, hiScore);
editor.commit();
MainActivity中的代码:
SharedPreferences prefs;
String dataName = "MyData";
String intName = "MyString";
int defaultInt = 0;
public static int hiScore;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs = getSharedPreferences(dataName,MODE_PRIVATE);
hiScore = prefs.getInt(intName, defaultInt);
TextView textHiScore =(TextView) findViewById(R.id.textHiScore);
textHiScore.setText("Hi: "+ hiScore);
}
答案 0 :(得分:2)
String intName = "MyInt";
MainActivity中的代码:
String intName = "MyString"; // change it to "MyInt"
在两个活动中保持intName
相同的参数。
答案 1 :(得分:2)
在GameActivity中:你检索到了&得分相同。
hiScore = prefs.getInt(intName, defaultInt);
// you should update hiScore here before put it in editor
editor.putInt(intName, hiScore);
答案 2 :(得分:0)
您正在保存hiScore
作为" MyInt"并尝试将其检索为" MyString"
答案 3 :(得分:0)
您无需初始化hiScore
在GameActivity中:
hiScore = prefs.getInt(intName, defaultInt);
editor.putInt(intName, hiScore);
你刚读取了prefs的值,没有初始化hiScore,所以hiScore值是defaultInt
在MainActivity中:
String intName = "MyString";
hiScore = prefs.getInt(intName, defaultInt);
prefs不包含关键eqauls“MyString”值,因此hiScore值为defaultInt