I have a small game that I’m working on, and I’m just working on updating the score, but I can’t get it to work properly.
Note: I cut pieces of my program to show here, I’ve got a whole bunch of other things that are being set, but they don’t touch the “score” at all, that’s why the code is a little shorthand.
My Code:
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;
}
});
}
I think its because you are creating a new shared preference Edit instance. ( as you call .edit() twice and commit an uneditted version)
Change your code…
To the following: