Reputation: 311
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?
Upvotes: 11
Views: 11572
Reputation: 13483
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
Upvotes: 18
Reputation: 1739
Use SharedPreferences
as,
To Save:
SharedPreferences settings;
SharedPreferences.Editor editor;
public static final String PREFS_NAME = "app_pref";
public static final String KEY_p_id = "KEY_test";
settings = getSharedPreferences(PREFS_NAME, 0);
editor = settings.edit();
editor.putString(Login_screen.KEY_test, values.get(0));
editor.commit();
To Remove:
editor.remove("KEY_test").commit();
Upvotes: 2
Reputation: 6925
Use SharedPreferences to save small chunk of app data. Check the developer's website for this.
Also check out this Tutorial for step by step guide.
Upvotes: 0
Reputation: 11915
You need to use SharedPreferences to save the settings of your app locally. Refer this link for more details : http://developer.android.com/reference/android/content/SharedPreferences.html
Upvotes: 2
Reputation: 10540
You should check out SharedPreferences. It's Android's way of persisting simple values. Or you could create a full database.
Upvotes: 0