简体   繁体   中英

Android SharedPreferences don't seem to work

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...

    SharedPreferences pref = getSharedPreferences("Prefs",
            Context.MODE_PRIVATE);
    new_total = new_total + change_in_points;
    pref.edit().putLong("total_points", new_total);
    pref.edit().commit();

To the following:

    SharedPreferences.Editor pref = getSharedPreferences("Prefs",
            Context.MODE_PRIVATE).edit();
    new_total = new_total + change_in_points;
    pref.putLong("total_points", new_total);
    pref.commit();

Each call to .edit() creates a new Editor.

Change

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

to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM