Search code examples
javaandroidlibgdx

How can I UPDATE or OVERWRITE the value of a preference in libGdx


I'm new to android development and I'm stuck on a part where I want the value of my high-score variable to be overwritten on my preference if the user surpasses the all-time high score. It's like a preference which will store the all-time high score of the user and will be updated if the user surpasses that particular high score.

What I did is:

  1. Initially assigned a value of 0 to my preference variable named HighScore and then commented it so initially, it will get 0. //preferences.putInteger("HighScore",0);

  2. Then I want to update the preference based on this condition where highScore variable is initialized to 0 on each run of the game and as the user plays the current score is allotted to the highScore variable.

if(preferences.getInteger("HighScore")<highScore){preferences.putInteger("HighScore",highScore)}

  1. When I log the value even after the condition is true still the preference's value does not update.

Solution

  • Step one obviously won't work in an actual game. Might as well do it properly from the beginning. When you get a preference value, you can also pass what the default value should be if it doesn't exist yet. So, you can do this exactly the same way every time the game loads, including the first time:

    int highScore = preferences.getInteger("HighScore", 0);
    

    After putting a value in the preferences, you have to call flush() for it to actually save it to disk.

    if (preferences.getInteger("HighScore", 0) < highScore) { 
        preferences.putInteger("HighScore", highScore);
        preferences.flush();
    }