Android SharedPreferences , how to save a simple int variable [duplicate]
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("your_int_key", yourIntValue);
editor.commit();
the you can get it as:
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
int myIntValue = sp.getInt("your_int_key", -1);
The SharedPreference
interface gives you access to the an xml file, and a easy way to modify it through its editor. The file is stored in /data/data/com.your.package/shared_prefs/
and you can access it onlu through this SharedPreference
API
public void SaveInt(String key, int value){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
public void LoadInt(){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
savedValue = sharedPreferences.getInt("key", 0);
}
If you want to save the variable somewhere, you have to write SaveInt("key", 5); With this you will save the value 5, while the first default value is 0. If you want to load it and use it in another activity, you have to write both of these methods there, and call LoadInt(); where you need the variable. The savedValue is a predefined integer (this needs to be declared everywhere you would like to use the saved variable)
This is the example of setting Boolean preferences. You can go with Integer also.
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
if (!prefs.getBoolean("firstTime", false)) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
Hope this might be helpful.