繁体   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