簡體   English   中英

Android SharedPreferences似乎不起作用

[英]Android SharedPreferences don't seem to work

我正在開發一個小游戲,我只是在更新分數,但是我無法使其正常工作。

注意:我在這里展示了程序的一部分,還設置了很多其他內容,但是它們根本沒有觸及“分數”,這就是代碼有些簡寫的原因

我的代碼:

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

        });
}

我認為是因為您正在創建新的共享首選項Edit實例。 (當您兩次調用.edit()並提交未編輯的版本時)

更改您的代碼...

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

每次調用.edit()都會創建一個新的Editor。

更改

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

Editor editor = prefs.edit();
editor.putLong("total_points", new_total);
editor.commit();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM