我正在开发一款小游戏,我正在更新分数,但无法让它正常工作。
注意:我剪切了我的程序 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/