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,我找不出錯誤出現在哪,請大家幫忙,謝謝。
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).