2

作業中の小さなゲームがあり、スコアの更新に取り組んでいますが、正しく動作させることができません。

注:ここに表示するためにプログラムの一部を切り取りました。設定されている他のものがたくさんありますが、それらは「スコア」にまったく触れていないため、コードは少し省略されています。

私のコード:

public class Start_Test extends Activity {

TextView total_points;
long new_total;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_three);
    total_points = (TextView) findViewById(R.id.points);
        SharedPreferences pref = getSharedPreferences("Prefs",
                Context.MODE_PRIVATE);
        new_total = pref.getLong("total_points", 0);
        setTouchListener();
    updateTotal(0);


}

public void updateTotal(long change_in_points) {
        SharedPreferences pref = getSharedPreferences("Prefs",
                Context.MODE_PRIVATE);
        new_total = new_total + change_in_points;
        pref.edit().putLong("total_points", new_total);
        pref.edit().commit();
        total_points.setText("" + new_total);

    }

public void setTouchListeners() {

        button.setOnTouchListener(new OnTouchListener() {
            SharedPreferences pref = getSharedPreferences("Prefs",
                    Context.MODE_PRIVATE);

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                updateTotal(25);
                return false;
            }

        });
}
4

2 に答える 2

3

これは、新しい共有設定Editインスタンスを作成しているためだと思います。(.edit()を2回呼び出して、編集されていないバージョンをコミットする場合)

コードを変更してください...

    SharedPreferences pref = getSharedPreferences("Prefs",
            Context.MODE_PRIVATE);
    new_total = new_total + change_in_points;
    pref.edit().putLong("total_points", new_total);
    pref.edit().commit();

次のように:

    SharedPreferences.Editor pref = getSharedPreferences("Prefs",
            Context.MODE_PRIVATE).edit();
    new_total = new_total + change_in_points;
    pref.putLong("total_points", new_total);
    pref.commit();
于 2013-01-12T21:53:01.047 に答える
2

.edit()を呼び出すたびに、新しいエディターが作成されます。

変化する

pref.edit().putLong("total_points", new_total);
pref.edit().commit();

Editor editor = prefs.edit();
editor.putLong("total_points", new_total);
editor.commit();
于 2013-01-12T21:54:38.230 に答える