How can I save the the settings of my app? Right now, for example, I have a togglebutton to turn on/off. But if I restart my phone, the toggle button is turned back on. Its not saving the settings if I completely close the app. Can I like the save the settings to the phone as cookies?
Use Shared Preferences. Like so:
Put this at the top of your class: public static final String myPref = "preferenceName";
Create these methods for use, or just use the content inside of the methods whenever you want:
public String getPreferenceValue()
{
SharedPreferences sp = getSharedPreferences(myPref,0);
String str = sp.getString("myStore","TheDefaultValueIfNoValueFoundOfThisKey");
return str;
}
public void writeToPreference(String thePreference)
{
SharedPreferences.Editor editor = getSharedPreferences(myPref,0).edit();
editor.putString("myStore", thePreference);
editor.commit();
}
You could call them like this:
writeToPreference("on"); // stores that the preference is "on"
writeToPreference("off"); // stores that the preference is "off"
if (getPreferenceValue().equals("on"))
{
// turn the toggle button on
}
else if (getPreferenceValue().equals("off"))
{
// turn the toggle button off
}
else if (getPreferenceValue().equals("TheDefaultValueIfNoValueFoundOfThisKey"))
{
// a preference has not been created
}
Note: you can do this with boolean
, integer
, etc.
All you have to do is change the String
storing and reading to boolean
, or whatever type you want.
Here is a link to a pastie with the code above modified to store a boolean
instead: http://pastie.org/8400737
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With