Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save app settings?

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?

like image 293
user2779837 Avatar asked Oct 14 '13 05:10

user2779837


1 Answers

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

like image 84
Michael Yaworski Avatar answered Sep 25 '22 23:09

Michael Yaworski