0

I need your help here.. I have the following code:

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();
}

But it still shows "0" if i restart the app. What did I do wrong?

4

2 回答 2

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)

于 2012-07-27T15:58:33.577 回答
0

放入mehrPunkte();_onCreate()

于 2012-07-27T15:55:26.577 回答