我需要你的帮助.. 我有以下代码:
public class GameActivity extends Activity {
TextView test1;
String punkte, points;
@Override
public void onCreate(Bundle savedInstanceState) {
test1 = (TextView) findViewById(R.id.test1);
punkte = points;
SharedPreferences load = getSharedPreferences(punkte, 0);
points = load.getString("punkte", "0");
test1.setText(points);
}
public void mehrPunkte() {
punkte = "3";
SharedPreferences load = getSharedPreferences(punkte, 0);
points = load.getString("punkte", "0");
test1.setText(points);
SharedPreferences save = getSharedPreferences(punkte, 0);
save.edit().putString("punkte", punkte).commit();
}
但如果重新启动应用程序,它仍会显示“0”。 我做错了什么?
答案 0 :(得分:3)
getSharedPreferences的第一个参数是其名称,您将其保存到不同的共享首选项,由punkte
变量的值指示。试试这个:
final private static String SHARED_PREF_ID = "My shared preferences";
@Override
public void onCreate(Bundle savedInstanceState) {
// ...
SharedPreferences load = getSharedPreferences(SHARED_PREF_ID, MODE_PRIVATE);
// ...
}
public void mehrPunkte() {
punkte = "3";
SharedPreferences load = getSharedPreferences(SHARED_PREF_ID, MODE_PRIVATE);
points = load.getString("punkte", "0");
test1.setText(points);
SharedPreferences save = getSharedPreferences(SHARED_PREF_ID, MODE_PRIVATE);
save.edit().putString("punkte", punkte).commit();
}
另外,使用常量来表示模式,而不是整数文字(MODE_PRIVATE,而不是0)
答案 1 :(得分:0)
将mehrPunkte();
放入onCreate()