Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Android Activity Lifecycle Introducing SharedPreferences Saving and Retrieving Data with SharedPreferences

Diego Marrs
Diego Marrs
8,243 Points

Purpose of 'PREFS_FILE'?

I'm not sure as to what the purpose of the 'PREFS_FILE' string is. We already have a value that stores our edittext, why do we need another value?

1 Answer

Jasmeet Singh
Jasmeet Singh
20,145 Points

As documented in the Android Developer Documentation for getSharedPreferences(), the full signature for the method is:

SharedPreferences getSharedPreferences (String name, int mode) The formal signature provides the name of the first parameter, name, which is information useful to the answer. The name parameter is the base name (without file extension) of an XML preferences file located in the private storage of the app.

For example, this call will return the SharedPreferences instance to allow reading and writing the app's settings.xml preferences file:

SharedPreferences sharedPrefs = getSharedPreferences("settings", Context.MODE_PRIVATE);

As indicated in the official documentation, the returned SharedPreferences object is a single-instance object, shared between all callers for the same file name. This means that a given call does not necessarily imply file IO to read a given preference, but may incur thread synchronization between threads in the same app.

The specified file will be created if it doesn't already exist prior to calling getSharedPreferences(). The second argument, mode, is the mode to use when creating the file, and should be set to Context.MODE_PRIVATE (or it's integer value 0); other mode values are not documented as allowed, and should not be used. As when creating any file, indicating a mode of Context.MODE_PRIVATE will locate the file in the app's private storage, as is expected for use with getSharedPreferences().