Preferences in Android

Android provides a bunch of, at times, confusing APIs for accessing shared preferences. Let’s discuss the same here. For reference, we will be using the image below. The image is taken using Android Device Manager and shows three preferences file used by our sample application.

Three preferences files

1. Context.getSharedPreferences(String name, int mode)

Creates a preference file of a given name.

Example: If we supply the name as “utilsPrefsFile”, it will create a preference file called utilsPrefsFile.xml (image above).

Note: The same file can be accessed from any activity within the application.

2. PreferenceManager.getDefaultSharedPreferences(Context ctxt)

This opens a preference file named “_preferences”. Internally, this method calls Context.getSharedPreferences(…).

Example: If the package name is “com.rudra.attendanceRegister”, a preferences file called com.rudra.attendanceRegister_preferences.xml would be created (image above).

Note: The same file can be accessed from any activity within the application.

3. Activity.getPreferences(int mode)

This opens a preference file specific to a particular activity. Android does so by removing the package name prefix form the Activity class’s fully qualified name. Internally, this method calls Context.getSharedPreferences(…).

Example: If the package name is “com.rudra.attendanceRegister” and the Activity’s name is “com.rudra.attendanceRegister.activities.MainActivity”, a preferences file called activities.MainActivity.xml would be created (image above).

Bonus

It is not too difficult to figure the about out. Just go through the source to see for yourself!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s