简体   繁体   中英

Android - SharedPreferences aren't saving when I restart the app

I'm using Android Studio to make a game, and my SharedPreferences which I'm using for a highscore aren't being saved when I reload the app. Within the app it works fine, but restarting sends the highscore back to the default value (0).

Setting my SharedPreferences in MainActivity:

    SharedPreferences settings = getSharedPreferences("GAME_DATA", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();

    if(currentTopic == 4){
        if(settings.getInt("HIGHSCORE", 0) < Math.round(scoreTotal)){
            editor.clear();

            editor.putInt("HIGHSCORE", Math.round(scoreTotal));
            editor.apply();
            editor.commit();
        }

        Intent homeIntent = new Intent(MainActivity.this, HomeActivity.class);
        homeIntent.putExtra("Score", Integer.toString(Math.round(scoreTotal)));
        startActivity(homeIntent);
        editor.commit();
        finish();

To clarify, the code does make it into the if statement. "scoreTotal" is the highscore which I am saving.

Getting my SharedPreferences in HomeActivity:

SharedPreferences settings = getSharedPreferences("GAME_DATA", Context.MODE_PRIVATE);
int highscore = settings.getInt("HIGHSCORE", 0);

Log.i("highscore", String.valueOf(highscore));

TextView tv_highscore = findViewById(R.id.tv_highscore);
tv_highscore.setText("Highscore: "+String.valueOf(highscore));

Where have I gone wrong?

Please let me know if I have forgotten to include something. I've tried many things from previous StackOverflow posts but to no avail. Thanks in advance.

EDIT: To clarify, my problem came from not being able to do SharedPreferences in that activity then get them from another. I used the intent extra message and did all the SharedPreferences in the HomeActivity and it worked. Hope this is able to help some people.

Try this instead:

SharedPreferences settings = getSharedPreferences("GAME_DATA", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
long score = Math.round(scoreTotal);

if(currentTopic == 4){
    if(settings.getInt("HIGHSCORE", 0) < score){
        editor.putInt("HIGHSCORE", score);
        editor.apply();
    }

    Intent homeIntent = new Intent(MainActivity.this, HomeActivity.class);
    homeIntent.putExtra("Score", Integer.toString(score));
    startActivity(homeIntent);
    finish();

I suspect that you do not need (or even really want) to call editor.clear(); since this (according the the Google Docs) will

Mark in the editor to remove all values from the preferences

.

And there is no need to call apply and commit one will do:

Google Docs:

Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself.

You can make a class for saving data like this

public class GameData {

private SharedPreferences preferences;
private SharedPreferences.Editor editor;

private Context context;

private int PRIVATE_MODE = 0;
private static final String PREF_NAME = "GAME_DATA";

public GameData(Context context){
    this.context = context;
    preferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
    editor = preferences.edit();
}

public void set(String key, boolean value){
    editor.putBoolean(key, value);
    editor.commit();
}

public void set(String key, String value){
    editor.putString(key, value);
    editor.commit();
}

public void set(String key, long value){
    editor.putLong(key, value);
    editor.commit();
}

public void set(String key, int value){
    editor.putInt(key, value);
    editor.commit();
}

public void set(String key, float value){
    editor.putFloat(key, value);
    editor.commit();
}


public float get(String key, float defaultValue){
    return preferences.getFloat(key, defaultValue);
}

public int get(String key, int defaultValue){
    return preferences.getInt(key, defaultValue);
}

public long get(String key, long defaultValue){
    return preferences.getLong(key, defaultValue);
}

public String get(String key, String defaultValue){
    return preferences.getString(key, defaultValue);
}

public boolean get(String key, boolean defaultValue){
    return preferences.getBoolean(key, defaultValue);
}
}

Then call the class to set/get your data

 private GameData gamedata;

 gamedata = new GameData(getApplicationContext());

 gamedata.set("HIGHSCORE",score); // FOR SET THE HIGHSCORE 

 int highscore = gamedata.get("HIGHSCORE", 0); // FOR GET THE HIGHSCORE

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