Shared Preferences Not Saving When I Compile My Code
Solution 1:
You're never setting the HighScore
integer to a value. I think maybe you think this line is doing something different than it actually is:
settings.getInt("HighScore", HighScore);
This calls the getInt function, which returns the value that has a key in the first paramater. If the value doesn't exist in the shared preferences, it returns HighScore instead. What you probably want is this:
HighScore = settings.getInt("HighScore", 0)
This will set HighScore to the value in the settings under "HighScore". If there is no value, then it'll return 0.
Make sure you also call LoadFromPref()
if you're going to call getHighScore()
!
Solution 2:
SharedPreferences used to store application level values. Whenever you do changes to code and again run the application, it creates shared preferences as new file & all previous data gets reset.
If you want score even after making some code changes and re-running application. It is better to store score in a file or DB and avoid creating file or copy database if it already exists in device. So that always you can get that data anytime. You can use content providers also.
Solution 3:
Here is a class I wrote for shared prefrences. It works fine in a simple game I am working on. You can simply use this singleton in your activity where you need to set/fetch the games high score. I use it for default shared prefrences, but it can also be used for multiple prefrences if needed.
/**
*
* This class is used for reading / writing data to a single prefrences
* file.
*
* Simply use setHighScore and getHighScore to get the score from a
* single prefrences file
*
*/publicenumSharedPrefrencesUtil {
UTIL;
privatefinal String HIGH_SCORE = "HighScore";
/**
* Gets a single shared prefrences file
*/public SharedPreferences getDefaultSharedPreference(Activity activity){
return activity.getPreferences(Context.MODE_PRIVATE);
}
/**
* Gets a specific shared preferences file if there are multiples in the application
*/public SharedPreferences getSharedPreferences(String preferenceFileName,
Context context){
return context.getSharedPreferences(preferenceFileName, Context.MODE_PRIVATE);
}
/**
* Sets a score into a the default prefrences file
*/publicvoidsetScore(Activity activity, int score){
activity.getPreferences(Context.MODE_PRIVATE).edit().putInt(HIGH_SCORE, score).commit();
}
/**
* Gets the score from the default prefrences file
*/publicintgetHighScore(Activity activity){
return activity.getPreferences(Context.MODE_PRIVATE).getInt(HIGH_SCORE, 0);
}
}
Post a Comment for "Shared Preferences Not Saving When I Compile My Code"