Android - How Do I Set A Preference In Code

50,830

Solution 1

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

Solution 2

I tried this but didn't work:

SharedPreferences settings = getSharedPreferences(String n, MODE_PRIVATE);

Try this instead:

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);

Solution 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);
}
Share:
50,830

Related videos on Youtube

Swati Garg
Author by

Swati Garg

A naive android app developer! :)

Updated on July 15, 2020

Comments

  • Swati Garg
    Swati Garg almost 4 years

    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?

  • tomash
    tomash over 14 years
    You can actually use one-liner: prefs.edit().putInt(key, value).commit();
  • Eugene van der Merwe
    Eugene van der Merwe over 13 years
    Any ideas how this differs from PreferenceActivity and do you maybe have a reference to an example of PreferenceActivity?
  • Twinone
    Twinone about 11 years
    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();
  • JustADev
    JustADev almost 10 years
    Although I'm 5 years late here, but using what @tomash 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?
  • ToolmakerSteve
    ToolmakerSteve almost 10 years
    @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...
  • ToolmakerSteve
    ToolmakerSteve almost 10 years
    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.)
  • ToolmakerSteve
    ToolmakerSteve almost 10 years
    @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.
  • JustADev
    JustADev almost 10 years
    @ToolmakerSteve 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.