386

I am using a PreferenceActivity to show some settings for my application. I am inflating the settings via a xml file so that my onCreate (and complete class methods) looks like this:

public class FooActivity extends PreferenceActivity {
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        addPreferencesFromResource(R.xml.preference);
    }
}

The javadoc of PreferenceActivity PreferenceFragment states that

These preferences will automatically save to SharedPreferences as the user interacts with them. To retrieve an instance of SharedPreferences that the preference hierarchy in this activity will use, call getDefaultSharedPreferences(android.content.Context) with a context in the same package as this activity.

But how I get the name of the SharedPreference in another Activity? I can only call

getSharedPreferences(name, mode)

in the other activity but I need the name of the SharedPreference which was used by the PreferenceActivity. What is the name or how can i retrieve it?

Edric
  • 24,639
  • 13
  • 81
  • 91
Dave
  • 3,983
  • 3
  • 17
  • 8

6 Answers6

747
import android.preference.PreferenceManager;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
// then you use
prefs.getBoolean("keystring", true);

Update

According to Shared Preferences | Android Developer Tutorial (Part 13) by Sai Geetha M N,

Many applications may provide a way to capture user preferences on the settings of a specific application or an activity. For supporting this, Android provides a simple set of APIs.

Preferences are typically name value pairs. They can be stored as “Shared Preferences” across various activities in an application (note currently it cannot be shared across processes). Or it can be something that needs to be stored specific to an activity.

  1. Shared Preferences: The shared preferences can be used by all the components (activities, services etc) of the applications.

  2. Activity handled preferences: These preferences can only be used within the particular activity and can not be used by other components of the application.

Shared Preferences:

The shared preferences are managed with the help of getSharedPreferences method of the Context class. The preferences are stored in a default file (1) or you can specify a file name (2) to be used to refer to the preferences.

(1) The recommended way is to use by the default mode, without specifying the file name

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);

(2) Here is how you get the instance when you specify the file name

public static final String PREF_FILE_NAME = "PrefFile";
SharedPreferences preferences = getSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE);

MODE_PRIVATE is the operating mode for the preferences. It is the default mode and means the created file will be accessed by only the calling application. Other two modes supported are MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE. In MODE_WORLD_READABLE other application can read the created file but can not modify it. In case of MODE_WORLD_WRITEABLE other applications also have write permissions for the created file.

Finally, once you have the preferences instance, here is how you can retrieve the stored values from the preferences:

int storedPreference = preferences.getInt("storedInt", 0);

To store values in the preference file SharedPreference.Editor object has to be used. Editor is a nested interface in the SharedPreference class.

SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();

Editor also supports methods like remove() and clear() to delete the preference values from the file.

Activity Preferences:

The shared preferences can be used by other application components. But if you do not need to share the preferences with other components and want to have activity private preferences you can do that with the help of getPreferences() method of the activity. The getPreference method uses the getSharedPreferences() method with the name of the activity class for the preference file name.

Following is the code to get preferences

SharedPreferences preferences = getPreferences(MODE_PRIVATE);
int storedPreference = preferences.getInt("storedInt", 0);

The code to store values is also the same as in case of shared preferences.

SharedPreferences preferences = getPreference(MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("storedInt", storedPreference); // value to store
editor.commit();

You can also use other methods like storing the activity state in database. Note Android also contains a package called android.preference. The package defines classes to implement application preferences UI.

To see some more examples check Android's Data Storage post on developers site.

Reinstate Monica
  • 2,767
  • 3
  • 31
  • 40
Pentium10
  • 204,586
  • 122
  • 423
  • 502
  • 60
    +1: u saved my day.. none of the tutorials/examples on the Internet tells about this. all they talk abt features and customizations, but not how to read it. – ankitjaininfo Sep 10 '10 at 20:18
  • btw, what's the file `name` in this case? – ankitjaininfo Sep 10 '10 at 20:19
  • 1
    See my update of the answer, and the filename is something like `package.prefs` but I am not sure. – Pentium10 Sep 10 '10 at 20:28
  • 1
    Thanks for the code. There is just one little thing that is confusing me: SharedPreference is an interface, so where is the actual code implemented that handles any method calls? – x1886x Jan 25 '11 at 13:23
  • @Pentium10 : Can the shared preferences file be accessed by the user from the sd card or where ever it is stored (not programmatically). Access its contents and modify them. Because I am planning to store the username and password of the user in the shared preferences if teh user does not logout of the application. – Ashwin Jul 29 '12 at 16:35
  • @Pentium10 But somebodies says getDefaultSharedPreference is ot working some times in some devices! ( http://stackoverflow.com/questions/10786172/android-getdefaultsharedpreferences ) – Dr.jacky Nov 10 '12 at 12:22
  • Thanks @Pentium10 for your nice answer. I just have a question. why you say `The recommended way is to use by the default mode`? where is it recommended? – Ali May 27 '13 at 12:13
  • 1
    Wish I had read this a week before wasting my time reading some stupid nerds answers/comments all over SE, who think they know when they actually don't.. Thanks @Pentium10, do you own any blog, thanks again, really appreciate it :) – Sanjeevcn Mar 14 '15 at 06:55
  • How do you use another preference file in the PreferenceActivity than the DefaultSharedPreferences? I want to use different settings per user. – Roel Sep 17 '15 at 13:40
  • 1
    Instead of using editor.commit(), you can also use editor.apply(). The difference is that commit() writes your changes synchronously and apply writes them asynchronously. This makes your UI faster. – Hashim Akhtar Feb 19 '16 at 14:50
  • @Pentium10 I have multiple sharedPreferences that defined in different activities. but one of them (is defined in adapter of recyclerview) lost when I press back button and go to last activity. do you have any idea? tnx. – MHSaffari Dec 20 '17 at 07:25
  • @MHSFisher ask as a new question, I don't have an idea. – Pentium10 Dec 20 '17 at 08:45
  • how do you set a custom `SharedPreference` file in a `PreferenceFragment` though? It seems that it saves preferences in the default file (i.e. app's package), what If I want to do something like `setSharedPreferences(PREF_FILE_NAME, MODE_PRIVATE)` ? Thanks – Javier Mendonça Sep 28 '18 at 13:36
28

If you don't have access to getDefaultSharedPreferenes(), you can use getSharedPreferences(name, mode) instead, you just have to pass in the right name.

Android creates this name (possibly based on the package name of your project?). You can get it by putting the following code in a SettingsActivity onCreate(), and seeing what preferencesName is.

String preferencesName = this.getPreferenceManager().getSharedPreferencesName();

The string should be something like com.example.projectname_preferences. Hard code that somewhere in your project, and pass it in to getSharedPreferences() and you should be good to go.

simeg
  • 1,889
  • 2
  • 26
  • 34
  • 1
    The source for activity reads: public SharedPreferences getPreferences(int mode) { return getSharedPreferences(getLocalClassName(), mode); } – Tatarize Oct 18 '15 at 22:10
22

Declare these methods first..

public static void putPref(String key, String value, Context context) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(key, value);
    editor.commit();
}

public static String getPref(String key, Context context) {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    return preferences.getString(key, null);
}

Then call this when you want to put a pref:

putPref("myKey", "mystring", getApplicationContext());

call this when you want to get a pref:

getPref("myKey", getApplicationContext());

Or you can use this object https://github.com/kcochibili/TinyDB--Android-Shared-Preferences-Turbo which simplifies everything even further

Example:

TinyDB tinydb = new TinyDB(context);

tinydb.putInt("clickCount", 2);
tinydb.putFloat("xPoint", 3.6f);
tinydb.putLong("userCount", 39832L);

tinydb.putString("userName", "john");
tinydb.putBoolean("isUserMale", true); 

tinydb.putList("MyUsers", mUsersArray);
tinydb.putImagePNG("DropBox/WorkImages", "MeAtlunch.png", lunchBitmap);
Ziem
  • 6,579
  • 8
  • 53
  • 86
kc ochibili
  • 3,103
  • 2
  • 25
  • 25
4

having to pass context around everywhere is really annoying me. the code becomes too verbose and unmanageable. I do this in every project instead...

public class global {
    public static Activity globalContext = null;

and set it in the main activity create

@Override
public void onCreate(Bundle savedInstanceState) {
    Thread.setDefaultUncaughtExceptionHandler(new CustomExceptionHandler(
            global.sdcardPath,
            ""));
    super.onCreate(savedInstanceState);

    //Start 
    //Debug.startMethodTracing("appname.Trace1");

    global.globalContext = this;

also all preference keys should be language independent, I'm shocked nobody has mentioned that.

getText(R.string.yourPrefKeyName).toString()

now call it very simply like this in one line of code

global.globalContext.getSharedPreferences(global.APPNAME_PREF, global.MODE_PRIVATE).getBoolean("isMetric", true);
hamish
  • 1,141
  • 1
  • 12
  • 21
  • 4
    What's the advantage of making keys language independent? They are never shown to the user, right? – Gerd Feb 19 '16 at 09:20
  • 1
    Please, for the love of god, never use an Activity as a global Context. If you have to use a global Context then please do so by using a custom Application class. – Thorben Nov 03 '16 at 12:14
  • 1
    @Thorben Agreed. Or simply `getApplicationContext()` – OneCricketeer Nov 03 '16 at 13:52
4

if you have a checkbox and you would like to fetch it's value ie true / false in any java file--

Use--

Context mContext;
boolean checkFlag;

checkFlag=PreferenceManager.getDefaultSharedPreferences(mContext).getBoolean(KEY,DEFAULT_VALUE);`
ugola
  • 300
  • 3
  • 18
0

Try following source code it worked for me

//Fetching id from shared preferences
    SharedPreferences sharedPreferences;
    sharedPreferences =getSharedPreferences(Constant.SHARED_PREF_NAME, Context.MODE_PRIVATE);
    getUserLogin = sharedPreferences.getString(Constant.ID_SHARED_PREF, "");
  • It's a strange answer. You have your own `Constant` class. But the accepted answer gives a right solution. – CoolMind Jul 10 '20 at 12:45
  • @CoolMind You can change as you want or, you can write
    `sharedPreferences =getSharedPreferences("SHREAD_PREF_NAME", Context.MODE_PRIVATE); getUserLogin = sharedPreferences.getString("ID", "value");`
    –  Oct 24 '20 at 15:47
  • Thanks, agree with you! – CoolMind Oct 25 '20 at 17:53