Einar Einar - 1 year ago 82
Java Question

Shared Preferences doesn't have to be created?

I'm trying to save information on an Android app I've made. I want to save a name, "Robert". For this I've been looking into Shared Preferences and I can't find a tutorial that explains how to create SharedPreferences.

All tutorials start like this:

SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);

But they don't explain where the getPreferences() take the object from.

When is this object (SharedPreferences object) created? Is it created along with the context? Is it created together with each activity?

I'm pretty new to Android, but an intermediate(minus) Java programmer.

Answer Source

SharedPreferences are created like this:

SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
 editor.putString("name", "Robert");
 editor.commit(); //Or use editor.apply()

Then you get them again like this:

SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); 
  String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.

So, the getString() gets the value you stored before, and returns the default value if you haven't stored a string for 'name' yet.

The object you store is saved in the system, and is constantly available to be grabbed.

UPDATE: The getSharedPreferences() method returns a SharedPreferences.Editor interface. According to the android docs

Interface used for modifying values in a SharedPreferences object. All changes you make in an editor are batched, and not copied back to the original SharedPreferences until you call commit() or apply()

UPDATE 2: This answer contains more info on the storage of SharedPreferences.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download