Android - How Do I Set A Preference In Code
Asked Answered
R

3

43

I have an Android application in which I have my preferences in an XML file, which works fine. I now want to set one of the preferences using code instead of displaying the entire preference screen, how would I go about doing this?

Rubin answered 16/2, 2009 at 2:26 Comment(0)
C
124

I assume by preferences you are referring to your application's preferences and not Android phone settings.

To store preferences between runs of you application you need to do the following

  1. Create a SharedPreferences object

    SharedPreferences settings = getSharedPreferences(String n, MODE_PRIVATE);
    

    String n identifies your preferences and the second argument is the mode they'll be accessed

  2. Instantiate an Editor object

    SharedPreferences.Editor editor = settings.edit();
    

    Note: do not try settings.editor.edit(), this will not make a persistent object and the code below will not work

  3. Write your preferences to the buffer

    editor.put...(String, value)
    

    There are numerous put function, putString, putBoolean, etc. The String is the key ("version", "good run") and the value is the value ("1.5.2", true)

  4. Flush the buffer

    editor.commit();
    

    This actually writes you put to the preferences. If your app crashes before this line then the preferences will not be written. There is also a documented bug: commit() is supposed to return a boolean indicating success or failure. Last I checked it always returned false.

These preferences will by stored on the phone and will only be accessible to your application.

More documentation is here

Chappell answered 16/2, 2009 at 6:2 Comment(7)
You can actually use one-liner: prefs.edit().putInt(key, value).commit();Incipient
Any ideas how this differs from PreferenceActivity and do you maybe have a reference to an example of PreferenceActivity?Auric
If you don't care about the return value, the docs say that since API level 9 you can better call apply(); instead of commit();Chimney
Although I'm 5 years late here, but using what @Incipient suggested failed when I wanted to create a new boolean value for my preference via java and not in the xml file. though using his line after the key was created did work. Can any one please explain what difference between Will answer and tomash? Don't they both do the same?Orin
@OmarBizreh - what tomash said (one liner) is exactly the same as lines 2-4 of Will's answer. (Of course you still need to create a preferences object (line 1)). I don't know what happens if you try line 1 BEFORE you've created that preference, and then are attempting to use that pref ob later -- is that what you did? If so, then the solution is: wherever in code you CREATE the preference (set the key), also set your class global that holds the pref ob. Or just be safe, and do line 1 every time...Courtly
@EugenevanderMerwe - PreferenceActivity or PreferenceFragment is used to display all preferences (or a group of preferences) to a user, so user can alter them. The OP is explicitly asking how he can set one or more preferences from code, without bringing up that GUI. So the difference is you the programmer setting a preference, versus the user setting a preference.Courtly
@Courtly My preference file was already created, but I wanted to add a new key via java. So using the 1 line code didn't work. I had to use tomash code in-order to be able to add a new preference key to my already created preference file.Orin
A
8

I tried this but didn't work:

SharedPreferences settings = getSharedPreferences(String n, MODE_PRIVATE);

Try this instead:

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
Agna answered 1/12, 2011 at 17:4 Comment(1)
It would be much more useful to say WHAT went wrong, instead of "didn't work". (It didn't compile? It crashed when you ran it? The returned list of preferences was empty?) Nevertheless, +1 for a good tip: Looking at my app, your line is what is used to access the settings from the MainActivity; the original answer's line can optionally be used to access the settings from code in a PreferenceFragment (a fragment that contains XML describing widgets for displaying/altering the preferences.)Courtly
A
3

You can save something in the sharedpreferences by using below code

public static void save(String valueKey, String value) {
    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(context);
    SharedPreferences.Editor edit = prefs.edit();
    edit.putString(valueKey, value);
    edit.commit();
    }

To read preferences:

public static String read(String valueKey, String valueDefault) {
    SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(context);
   return prefs.getString(valueKey, valueDefault);
}
Andonis answered 29/4, 2016 at 5:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.