I like to create a simple helper class to deal with the saving and loading of values. That way you can keep all of the keys on one place.
public class PreferencesHelper {
private SharedPreferences prefs;
private static final String FILE_NAME = "file_name";
public static final String KEY_HIGH_SCORE = "high_score";
public PreferencesHelper(Context context) {
prefs = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
}
/**
* Save the specified value to the shared preferences
*
* @param key
* The key of the value you wish to load
* @param defValue
* The value to store
*/
public void save(String key, int value) {
prefs.edit().putInt(key, value).commit();
}
/**
* Load the specified value from the shared preferences
*
* @param key
* The key of the value you wish to load
* @param defValue
* The default value that will be returned if nothing is found
*/
public int loadInt(String key, int defValue) {
return prefs.getInt(key, defValue);
}
}
Then, in your activity you just write:
PreferencesHelper prefs = new PreferencesHelper(this);
// Save
prefs.save(PreferencesHelper.KEY_HIGH_SCORE, 25000);
//Load
prefs.loadInt(PreferencesHelper.KEY_HIGH_SCORE, 0);