java - Android SharedPreferences 似乎不起作用

标签 java android sharedpreferences

我正在开发一款小游戏,我正在更新分数,但无法让它正常工作。

注意:我剪切了我的程序 fragment 以在此处显示,我已经设置了一大堆其他东西,但它们根本不触及“分数”,这就是为什么代码有点简写

我的代码:

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() 两次并提交未经编辑的版本时)

更改您的代码...

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

关于java - Android SharedPreferences 似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14298282/

相关文章:

java - 离开 SettingsActivity 时应用强制关闭

java - 关闭使用 FileOutputStream 创建的文件,以便进行下一次删除

java - facebook:为什么我不能从应用程序向用户发送电子邮件?

java - 我可以以某种方式创建类型参数列表吗?

android - 访问第二个项目的 "Remote config"

android - 如何在偏好 Activity 上有自定义对话框?

java - Eclipse Mars - 当前显示的页面包含无效值

java - 如何在对话框子类内单击按钮时使用“创建选择器”

java - 重新启动应用程序后更新共享首选项

java - 如何将 SharedPreferences 与微调器一起使用